單鏈隊列方法用于對隊列中的元素進行入、出編程,顯示隊列中的元素,要求整個過程以菜單選擇的形式出現,本文是武林技術頻道小編為大家整理的詳解C語言單鏈隊列的演示,希望對你有幫助!
1.概述:
C語言的隊列(queue),是指先進先出(FIFO, First-In-First-Out)的線性表。在具體應用中通常用鏈表或者數組來實現。隊列只允許在后端(稱為rear)進行插入操作,在前端(稱為front)進行刪除操作。
而單鏈隊列使用鏈表作為基本數據結果,因此不存在偽溢出的問題,隊列長度也沒有限制。但插入和讀取的時間代價會比較高
2.實例代碼:
/* 單鏈隊列——隊列的鏈式存儲結構 */typedef struct QNode{ QElemType data; struct QNode *next;}QNode,*QueuePtr;typedef struct{ QueuePtr front,rear; /* 隊頭、隊尾指針 */}LinkQueue;/* 鏈隊列的基本操作(9個) */void InitQueue(LinkQueue *Q){ /* 構造一個空隊列Q */ Q->front=Q->rear=malloc(sizeof(QNode)); if(!Q->front) exit(OVERFLOW); Q->front->next=NULL;}void DestroyQueue(LinkQueue *Q){ /* 銷毀隊列Q(無論空否均可) */ while(Q->front) { Q->rear=Q->front->next; free(Q->front); Q->front=Q->rear; }}void ClearQueue(LinkQueue *Q){ /* 將Q清為空隊列 */ QueuePtr p,q; Q->rear=Q->front; p=Q->front->next; Q->front->next=NULL; while(p) { q=p; p=p->next; free(q); }}Status QueueEmpty(LinkQueue Q){ /* 若Q為空隊列,則返回TRUE,否則返回FALSE */ if(Q.front->next==NULL) return TRUE; else return FALSE;}int QueueLength(LinkQueue Q){ /* 求隊列的長度 */ int i=0; QueuePtr p; p=Q.front; while(Q.rear!=p) { i++; p=p->next; } return i;}Status GetHead_Q(LinkQueue Q,QElemType *e){ /* 若隊列不空,則用e返回Q的隊頭元素,并返回OK,否則返回ERROR */ QueuePtr p; if(Q.front==Q.rear) return ERROR; p=Q.front->next; *e=p->data; return OK;}void EnQueue(LinkQueue *Q,QElemType e){ /* 插入元素e為Q的新的隊尾元素 */ QueuePtr p= (QueuePtr)malloc(sizeof(QNode)); if(!p) /* 存儲分配失敗 */ exit(OVERFLOW); p->data=e; p->next=NULL; Q->rear->next=p; Q->rear=p;}Status DeQueue(LinkQueue *Q,QElemType *e){ /* 若隊列不空,刪除Q的隊頭元素,用e返回其值,并返回OK,否則返回ERROR */ QueuePtr p; if(Q->front==Q->rear) return ERROR; p=Q->front; /* 指向頭結點 */ *e=p->data; Q->front=p->next; /* 摘下頭節點 */ if(Q->rear==p) Q->rear=Q->front; free(p); return OK;}void QueueTraverse(LinkQueue Q,void(*vi)(QElemType)){ /* 從隊頭到隊尾依次對隊列Q中每個元素調用函數vi() */ QueuePtr p; p=Q.front->next; while(p) { vi(p->data); p=p->next; } printf("/n");}
以上文章就是武林技術頻道小編介紹的詳解C語言單鏈隊列的演示,希望對大家有所幫助,切記要了解透徹,確保安全后再進行相關操作。?
|
新聞熱點
疑難解答
圖片精選