队列的链表实现

queue.h:

 1 #ifndef QUEUE_H_INCLUDED
 2 #define QUEUE_H_INCLUDED
 3 struct Node;
 4 typedef struct Node QNode;
 5 struct Queue;
 6 typedef struct Queue *PtrQ;
 7 
 8 PtrQ CreateQueue();
 9 void MakeEmpty(PtrQ Q);
10 int DeQueue(PtrQ Q);
11 void EnQueue(int X, PtrQ Q);
12 
13 #endif // QUEUE_H_INCLUDED

实现文件

implementation.c:

 1 #include<stdio.h>
 2 #include "queue.h"
 3 
 4 typedef struct Node{
 5     int Data;
 6     struct Node *Next;
 7 }QNode;
 8 
 9 typedef struct Queue{
10     QNode *Rear;
11     QNode *Front;
12 }*PtrQ;
13 
14 PtrQ CreateQueue(){
15     PtrQ Q;
16     Q = malloc(sizeof(struct Queue));
17     MakeEmpty(Q);
18     return Q;
19 }
20 
21 void MakeEmpty(PtrQ Q) {
22     Q->Rear = Q->Front = NULL;
23 }
24 
25 int DeQueue(PtrQ Q) {
26     QNode *FirstCell;
27     int FirstElem;
28     if(Q->Front == NULL){
29         printf("Error, EmptyQueue!");
30         return -1;
31     }
32     FirstCell = Q->Front;
33     if(Q->Rear == Q->Front) {
34         Q->Rear = Q->Front = NULL;
35     } else {
36         Q->Front = Q->Front->Next;
37     }
38     FirstElem = FirstCell->Data;
39     free(FirstCell);
40     return FirstElem;
41 }
42 
43 void EnQueue(int X, PtrQ Q) {
44     QNode *TmpCell;
45     TmpCell = malloc(sizeof(struct Node));
46     TmpCell->Next = NULL;
47     TmpCell->Data = X;
48     if(Q->Front == NULL) {
49         Q->Rear = TmpCell;
50         Q->Front = TmpCell;
51     } else if(Q->Front == Q->Rear) {
52         Q->Rear = TmpCell;
53         Q->Front->Next = Q->Rear;
54     } else{
55         Q->Rear->Next = TmpCell;
56         Q->Rear = TmpCell;
57     }
58 }

测试文件:

main.c:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include "queue.h"
 4 
 5 int main()
 6 {
 7     PtrQ Q;
 8     int a, b, c;
 9     Q = CreateQueue();
10     EnQueue(1, Q);
11     EnQueue(2, Q);
12     a = DeQueue(Q);
13     b = DeQueue(Q);
14     printf("%d ", a);
15     EnQueue(3, Q);
16     c = DeQueue(Q);
17     printf("%d ", b);
18     printf("%d", c);
19     return 0;
20 }

 

posted on 2015-09-23 11:20  川川的小铁柱  阅读(149)  评论(0)    收藏  举报

导航