队列 - 链表实现

队列的链表实现比数组实现要难一些。队列的链表实现比栈的链表实现也要难一些。

代码如下:

  1 #include <cstdio>
  2 #include <cstdlib>
  3 
  4 typedef int itemType;
  5 struct Node;
  6 struct Queue;
  7 typedef struct Node *pNode;
  8 typedef Queue *queue;
  9 
 10 struct Node {
 11     itemType item;
 12     pNode next;
 13 };
 14 
 15 struct Queue {
 16     pNode front;
 17     pNode rear;
 18 };
 19 
 20 int
 21 IsEmpty(queue q)
 22 {
 23     return q->front == NULL;
 24 }
 25 
 26 void
 27 Pop(queue q)
 28 {
 29     pNode tmp;
 30     if (!IsEmpty(q)) {
 31         tmp = q->front;
 32         q->front = q->front->next;
 33         free(tmp);
 34     }
 35 }
 36 
 37 itemType
 38 Top(queue q)
 39 {
 40     if (!IsEmpty(q)) {
 41         return q->front->item;
 42     } else {
 43         printf("Queue is empty!\n");
 44         return -1;
 45     }
 46 }
 47 
 48 void
 49 Push(itemType x, queue q)
 50 {
 51     pNode tmp;
 52     
 53     tmp = (pNode)malloc(sizeof(struct Node));
 54     if (tmp == NULL) {
 55         printf("Out of space!\n");
 56         return;
 57     }
 58     if (IsEmpty(q)) {
 59         tmp->item = x;
 60         tmp->next = NULL;
 61         q->front = tmp;
 62         q->rear = tmp;
 63     } else {
 64         tmp->item = x;
 65         tmp->next = NULL;
 66         q->rear->next = tmp;
 67         q->rear = tmp;
 68     }
 69 }
 70 
 71 void
 72 MakeEmpty(queue q)
 73 {
 74     if (q == NULL) {
 75         printf("Must use Createqueue first!\n");
 76         return;
 77     } else {
 78         while (!IsEmpty(q)) {
 79             Pop(q);
 80         }
 81     }
 82 }
 83 
 84 queue
 85 CreateQueue(void)
 86 {
 87     queue q;
 88     
 89     q = (queue)malloc(sizeof(struct Queue));
 90     if (q == NULL) {
 91         printf("out of space!\n");
 92         return NULL;
 93     }
 94     q->front = NULL;
 95     q->rear = NULL;
 96     MakeEmpty(q);
 97     return q;
 98 }
 99 
100 void
101 DisposeQueue(queue q)
102 {
103     pNode tmp;
104     
105     while(!IsEmpty(q)) {
106         Pop(q);
107     }
108     free(q);
109 }
110 
111 int
112 main(int argc, char** argv)
113 {
114     queue q;
115     
116     q = CreateQueue();
117     Push(2, q);
118     Push(3, q);
119     Push(4, q);
120     Pop(q);
121     Pop(q);
122     Pop(q);
123 
124     printf("%d\n", Top(q));
125     
126     //DisposeQueue(q);
127     //q = NULL;
128     
129     system("pause");
130     return(0);
131 }

 

posted @ 2014-11-04 20:27  nipan  阅读(183)  评论(0编辑  收藏  举报