1. 程式人生 > >資料結構——佇列的鏈式儲存結構以及實現

資料結構——佇列的鏈式儲存結構以及實現

佇列也是一種特殊的線性表,只允許在一端進行插入操作,在另一端進行刪除操作。允許插入的一段為對尾,允許刪除的一端為隊頭。本次記錄的是佇列的鏈式儲存結構以及實現。該儲存結構有兩個指標,一個指向頭節點,稱為頭指標(front);一個指向隊尾,稱為尾指標(rear)。當front==rear時,表示空佇列。當需要在佇列中插入元素時,需要將隊尾結點指向新插入的結點,然後將尾指標指向新插入的結點。當要在佇列中進行刪除操作時,只需讓頭指標指向隊頭結點的下一個結點即可。實現程式碼如下:

#include "iostream"
using namespace std;
#define OK 1
#define OVERFLOW -1
#define ERROR 0 typedef int ElemType; typedef int Status; typedef struct QNode { ElemType data; struct QNode *next; }QNode,*QueuePtr; typedef struct { QueuePtr front;//隊頭指標 QueuePtr rear;//隊尾指標 }LinkQueue; //佇列鏈式表示 //佇列初始化 Status InitQueue(LinkQueue &Q) { Q.front = Q.rear = (QueuePtr)malloc
(sizeof(QNode)); if(!Q.front) exit(OVERFLOW); Q.front->next = NULL; Q.rear->next = NULL; return OK; } //刪除元素 Status DeleteQueue(LinkQueue &Q, ElemType &e) { if (Q.front == Q.rear) return ERROR;//判斷是否是空佇列 QueuePtr p; p = Q.front->next; //將要刪除的對頭結點暫存給p e = p->data;//儲存將要刪除結點的值
Q.front->next = p->next;//將元佇列頭後繼p->bext賦給頭結點後繼 if (Q.rear == p) Q.rear = Q.front;//刪除元素之前,佇列中只有一個元素。 free(p); return OK; } //插入元素到佇列中 Status InsertQueue(LinkQueue &Q, ElemType e) { QueuePtr p=(QueuePtr)malloc(sizeof(QNode)); if (!p) exit(OVERFLOW); p->data = e; p->next = NULL; Q.rear->next = p;//將p插入尾指標所指向的隊尾結點後面 Q.rear = p;//尾指標指向新插入的結點 return OK; } //遍歷佇列中的元素 Status VisitQueue(LinkQueue Q) { if (Q.front == Q.rear)//如果是空佇列.. { cout << "空佇列" << endl; return ERROR; } QueuePtr p; p = Q.front->next;//p指向隊頭結點 while (p)//p不為空時 { cout << p->data << " ";//輸出p指向的結點的值 p = p->next;//指標後移 } cout << endl; return OK; } int main() { LinkQueue Q; InitQueue(Q); InsertQueue(Q, 1); InsertQueue(Q, 2); InsertQueue(Q, 3); InsertQueue(Q, 4); InsertQueue(Q, 5); VisitQueue(Q); int e; DeleteQueue(Q, e); InsertQueue(Q, 6); VisitQueue(Q); getchar(); return 0; }

執行結果:
這裡寫圖片描述