鏈隊列
阿新 • • 發佈:2017-11-26
sin 註意 pre amp 是否為空 bool init pty ron
#include<bits/stdc++.h> #define OK 1 #define ERROR 0 using namespace std; typedef int Status; typedef int ElemType; typedef struct QNode { ElemType data; struct QNode *next; }*Node; typedef struct { Node front; Node rear; int len; }LinkQueue; ///初始化 Status Init(LinkQueue &Q) { Node p; p=(Node)malloc(sizeof(QNode)); if(p) { Q.front=Q.rear=p; p->next=NULL; Q.len=0; return OK; } else return ERROR; } ///判斷隊列是否為空 bool EmptyQueue(LinkQueue Q) { if(Q.front == Q.rear) { return true; } else {return ERROR; } } ///入隊 Status Push(LinkQueue &Q, ElemType e) { Node p; p=(Node)malloc(sizeof(QNode)); if(!p) exit(1); p->data=e; p->next=NULL; ///註意此處,剛開始沒有想到,只有 p->next = NULL 才確定p是尾部 Q.rear->next=p; Q.rear=p; Q.len++; returnOK; } ///出隊 int Pop(LinkQueue &Q,ElemType &e) { if(Q.front == Q.rear) { printf("鏈隊列沒有元素\n"); return ERROR; } else { Node p; p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.rear == p) Q.rear=Q.front; free(p); Q.len--; return e; } } ///求隊列長度 int QueueLength(LinkQueue Q) { return Q.len; } ///銷毀隊列 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) { DestroyQueue(Q); Init(Q); return OK; } /*另一種思路寫法 Status ClearQueue(LinkQueue &Q) { Node p,q; p=Q.front->next; while(p) { q=p; p=p->next; free(q); } Q.rear=Q.front; Q.len=0; return OK; }另一種思路寫法*/ Status Print(LinkQueue Q) { Node p; p=Q.front->next; while(p!=Q.rear) { printf("%d--",p->data); p=p->next; } printf("%d\n",Q.rear->data); return OK; } int main() { int n; LinkQueue Q; Init(Q); printf("請輸入入隊元素(以0為結束標誌):"); while(~scanf("%d",&n)) { if(n == 0) break; Push(Q,n); } if(EmptyQueue(Q)) printf("YES,kong\n"); else printf("NO kong\n"); printf("隊列的長度為:%d\n",QueueLength(Q)); printf("遍歷隊首到隊尾的元素:\n"); Print(Q); printf("------------------------------\n"); int e; printf("出隊的隊首元素為:%d\n",Pop(Q,e)); printf("隊列的長度為:%d\n",QueueLength(Q)); printf("遍歷隊首到隊尾的元素:\n"); Print(Q); printf("------------------------------\n"); printf("Clear queue...\n"); ClearQueue(Q); if(EmptyQueue(Q)) printf("YES,kong\n"); else printf("NO kong\n"); printf("------------------------------\n"); return 0; } /* 1 2 3 4 5 0 */
鏈隊列