链队列
Posted sgawscd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链队列相关的知识,希望对你有一定的参考价值。
1 //Queue.h 2 3 #ifndef QUEUE_H 4 #define QUEUE_H 5 6 #define OK 1 7 #define ERROR 0 8 typedef int QElemType; 9 typedef int Status; 10 11 typedef struct QNode { 12 QElemType data; 13 struct QNode *next; 14 }QNode,*QueuePtr; 15 typedef struct { 16 QueuePtr front; //队头指针 17 QueuePtr rear; //队尾指针 18 }LinkQueue; 19 20 Status InitQueue(LinkQueue &Q); 21 Status DestroyQueue(LinkQueue &Q); 22 Status ClearQueue(LinkQueue &Q); 23 Status QueueEmpty(LinkQueue Q); 24 int QueueLength(LinkQueue Q); 25 Status GetHead(LinkQueue Q, QElemType &e); 26 Status EnQueue(LinkQueue &Q, QElemType e);//插入队尾元素 27 Status DeQueue(LinkQueue &Q, QElemType &e);//删除队头元素 28 Status QueueTraverse(LinkQueue Q); 29 #endif
//Queue.cpp #include"Queue.h" #include<iostream> #include<cstdlib> using namespace std; Status InitQueue(LinkQueue &Q) { //构造空队列 Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode)); if (!Q.front) exit(OVERFLOW); Q.front->next = NULL; return OK; } Status DestroyQueue(LinkQueue &Q) { while (Q.front) { Q.rear = Q.front->next; free(Q.front); Q.front = Q.rear; } return OK; } Status ClearQueue(LinkQueue &Q) { // Q.rear = Q.front; DestroyQueue(Q); InitQueue(Q); return OK; } Status QueueEmpty(LinkQueue Q) { if (Q.front == Q.rear) return OK; return ERROR; } int QueueLength(LinkQueue Q) { QueuePtr temp = Q.front; int i = 0; while (temp != Q.rear) { temp = temp->next; i++; } return i; } Status GetHead(LinkQueue Q, QElemType &e) { if (QueueEmpty(Q)) return ERROR; e = Q.front->next->data; return OK; } Status EnQueue(LinkQueue &Q, QElemType e) { QueuePtr P = (QueuePtr)malloc(sizeof(QNode)); if (!P) exit(OVERFLOW); P->data = e; P->next = NULL; Q.rear->next = P; Q.rear = P; return OK; } Status DeQueue(LinkQueue &Q, QElemType &e) { if (QueueEmpty(Q)) return ERROR; QueuePtr P = Q.front->next; e = P->data; Q.front->next = P->next; if (Q.rear == P) Q.rear = Q.front; free(P); return OK; } Status QueueTraverse(LinkQueue Q) { if (QueueEmpty(Q)) { cout << "Empty!" << endl; return ERROR; } QueuePtr temp = Q.front; while (temp != Q.rear) { temp = temp->next; cout << temp->data << " "; } cout << endl; return OK; }
//Main.cpp #include"Queue.h" #include<iostream> using namespace std; int main() { LinkQueue LQ; InitQueue(LQ); QElemType temp; QElemType temp2; cout << QueueEmpty(LQ) << endl; EnQueue(LQ, 2); EnQueue(LQ, 7); EnQueue(LQ, 1); EnQueue(LQ, 5); EnQueue(LQ, 2); EnQueue(LQ, 0); QueueTraverse(LQ); DeQueue(LQ, temp); cout << "temp = " << temp << endl; QueueTraverse(LQ); cout << "length:" << QueueLength(LQ)<<endl; GetHead(LQ, temp); cout << "head = " << temp << endl; // DestroyQueue(LQ); ClearQueue(LQ); cout << "after Destroy LQ: " << endl; QueueTraverse(LQ); cout << "length:" << QueueLength(LQ) << endl; GetHead(LQ, temp2); cout << "head = " << temp2 << endl; system("pause"); return 0; }
以上是关于链队列的主要内容,如果未能解决你的问题,请参考以下文章