数据结构-链队列基本操作

都是些基本操作,有兴趣的可以看看。

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 typedef struct QNode {
 4     int data;
 5     struct QNode *next;
 6 }QNode,*QueuePtr;
 7 typedef struct{
 8     QueuePtr front;
 9     QueuePtr rear;
10 
11 }LinkQueue;
12 //初始化
13 int InitQueue(LinkQueue &Q) {
14     Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
15     if (!Q.front) {
16         printf("空间开辟失败\n");
17         return 0;
18     }
19     Q.front->next = NULL;
20 }
21 //销毁队列
22 void DestoryQueue(LinkQueue &Q) {
23     while (Q.front) {
24         Q.rear = Q.front->next;
25         free(Q.front);
26         Q.front = Q.rear;
27     }
28     printf("销毁成功\n");
29 }
30 //插入
31 int EnQueue(LinkQueue &Q,int e) {
32     QueuePtr q;
33     q = (QueuePtr)malloc(sizeof(QNode));
34     if (!q) {
35         return 0;
36     }
37     q->data = e;
38     q->next = NULL;
39     Q.rear->next = q;
40     Q.rear = q;
41 }
42 //删除
43 void DeQueue(LinkQueue &Q) {
44     if (Q.front == Q.rear) {
45         printf("队列为空\n");
46     }
47     QueuePtr p;
48     p = (QueuePtr)malloc(sizeof(QNode));
49     p = Q.front->next;
50     Q.front->next = p->next;
51     if (Q.rear == p) {
52         Q.front == Q.rear;
53     }
54 }
55 //遍历
56 void QueueTraverse(LinkQueue Q) {
57     QueuePtr p;
58     p = (QueuePtr)malloc(sizeof(QNode));
59     if (Q.front == Q.rear) {
60         printf("队列为空\n");
61     }
62     else {
63         p = Q.front->next;
64         while (p) {
65             printf(" %d", p->data);
66             p = p->next;
67         }
68         printf("\n");
69     }
70 }
71 int main() {
72     LinkQueue Q;
73     InitQueue(Q);
74     for (int i = 0; i < 4; i++) {
75         EnQueue(Q, i);
76     }
77     QueueTraverse(Q);
78     DeQueue(Q);
79     QueueTraverse(Q);
80     DestoryQueue(Q);
81     QueueTraverse(Q);
82     return 0;
83 }

猜你喜欢

转载自www.cnblogs.com/CUCYG/p/10220301.html