C語言實現隊列


C語言實現隊列

 

原理:

  • 通過單鏈表實現的隊列,隊列就是一個尾插頭刪的單鏈表,先實現一個鏈表 ,再實現一個隊列包括隊頭指針和隊尾指針
  • 在這里插入圖片描述
 1 #ifndef Queue_h
 2 #define Queue_h
 3 
 4 #include <stdio.h>
 5 
 6 typedef int QDataType;        //數據類型
 7 
 8 typedef struct ListNode        //通過鏈表實現的
 9 {
10     QDataType _data;
11     struct ListNode* _pNext;
12 }ListNode,*pListNode;
13 
14 typedef struct Queue
15 {
16     pListNode _pHead;        //頭指針
17     pListNode _pTail;        //尾指針
18 }Queue;
19 
20 void QueueInit(Queue* q);        //初始化
21 void QueuePush(Queue* q, QDataType d);//進隊列(尾插)
22 void QueuePop(Queue* q);        //出隊列(頭刪)
23 int QueueSize(Queue* q);        //求隊列大小
24 int QueueEmpty(Queue* q);        //隊列判空
25 QDataType Front(Queue* q);        //獲取隊頭元素
26 QDataType Back(Queue* q);        //獲取隊尾元素
27 
28 #endif /* Queue_h */
View Code
 1 #include "Queue.h"
 2 #include <assert.h>
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 
 6 pListNode BuyNode(QDataType d)
 7 {
 8     pListNode new = malloc(sizeof(ListNode));
 9     new->_data = d;
10     new->_pNext = NULL;
11     return new;
12 }
13 
14 void QueueInit(Queue* q)
15 {
16     assert(q);
17     q->_pHead = BuyNode(0);
18     q->_pTail =q->_pHead;
19 }
20 
21 void QueuePush(Queue* q, QDataType d)
22 {
23     assert(q);
24     q->_pTail->_pNext = BuyNode(d);
25     q->_pTail = q->_pTail->_pNext;
26     
27 }
28 
29 void QueuePop(Queue* q)
30 {
31     pListNode dNode = q->_pHead->_pNext;
32     if (dNode)
33     {
34         q->_pHead->_pNext = dNode->_pNext;
35         if (q->_pHead->_pNext == NULL) {
36             q->_pTail = q->_pHead;
37         }//如果只有一個元素,刪完后ptail會懸空
38         free(dNode);
39     } 
40 }
41 
42 int QueueSize(Queue* q)
43 {
44     assert(q);
45     pListNode pre = q->_pHead->_pNext;
46     int count = 0;
47     while (pre)
48     {
49         count++;
50         pre = pre->_pNext;
51     }
52     return count;
53 }
54 int QueueEmpty(Queue* q)
55 {
56     return NULL == q->_pHead->_pNext;
57     
58 }
59 QDataType Front(Queue* q)
60 {
61     return q->_pHead->_pNext->_data;
62 }
63 QDataType Back(Queue* q)
64 {
65     return q->_pTail->_data;
66 }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM