数据结构之队列
简单实现数据结构队列
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <iostream> #define OK 1 #define OVERFLOW -1 #define ERROR -1 #define TRUE 1 #define FALSE 0 using namespace std; struct queueNode{ int data; struct queueNode *next; }; typedef struct { struct queueNode *fron; struct queueNode *rear; }LinkQueue; int InitQueue(LinkQueue &Q){ Q.fron = Q.rear = (struct queueNode*)malloc(sizeof(struct queueNode)); if(!Q.fron) return OVERFLOW; Q.fron->next = NULL; return OK; } int queueEmpty(LinkQueue &Q){ if(Q.fron == Q.rear) return TRUE; return FALSE; } int insertQueue(LinkQueue &Q, int e) { struct queueNode *p; p = (struct queueNode *)malloc(sizeof(struct queueNode)); if(!p) return OVERFLOW; p->data = e; p->next = NULL; Q.rear->next = p; Q.rear = p; return OK; } int deleteQueue(LinkQueue &Q, int &e) { struct queueNode *p; if(Q.fron == Q.rear) return OVERFLOW; p = Q.fron->next; e = p->data; Q.fron->next = p->next; if(p == Q.rear) Q.rear = Q.fron; free(p); return OK; } int GetFront(LinkQueue &Q, int &e) { if(Q.fron == Q.rear) return OVERFLOW; e = Q.fron->next->data; return OK; } // test int main() { LinkQueue Q; int e; InitQueue(Q); for(int i=0; i<10; i++) if(insertQueue(Q, i+1) != OK) cout << "出错" << endl; if(!queueEmpty(Q)) cout << "队列非空" << endl; else cout << "队列空" << endl; if(GetFront(Q, e) != OK) cout << "出错" << endl; else cout << e << endl; for(int i=0; i<10; i++) if(deleteQueue(Q, e)!= OK) cout <<"出错"<< endl; else cout << e << endl; return 0; }