1 #include <stdio.h>
2 #include <malloc.h>
3
4 #define OK 1
5 #define ERROR 0
6 typedef int Status;
7 typedef int QElemType; //队列中的元素类型
8
9 typedef struct QNode //队列中的节点类型
10 {
11 QElemType data;
12 struct QNode* next;
13 }QNode, * QueuePtr;
14
15 typedef struct
16 {
17 QueuePtr front;
18 QueuePtr rear;
19 }LinkQueue;
20 //定义连队列类型int main()
21
22 Status InitQueue(LinkQueue& Q);//初始化空队列
23 Status GetHead(LinkQueue Q, QElemType& e); //获取队头元素的值并返回在e中
24 Status EnQueue(LinkQueue& Q, QElemType e);//将元素e入队
25 Status DeQueue(LinkQueue& Q, QElemType& x);//将队头元素出队 ,返回在e中
26 int QueueLength(LinkQueue Q); //求队列的长度
27
28 int main()
29 {
30 LinkQueue Q;
31 QElemType e;
32 int m;
33
34 InitQueue(Q);
35 scanf("%d",&m);//输入标志数据m
36 while(m!=0) //m=0表示操作结束
37 {
38 if(m==1) //m=1表示入队
39 {
40 scanf("%d",&e);
41 EnQueue(Q,e);
42 }
43 else if(m==2)//m=2表示出队
44 {
45 DeQueue(Q,e);
46 }
47 scanf("%d",&m);
48 }
49 printf("length=%d\n",QueueLength(Q)); //输出队列长度
50 if (GetHead(Q,e)==OK) //取队头元素的值并输出
51 printf("first=%d",e);
52 else
53 printf("first=NULL");
54 return 0;
55 }
56
57 Status InitQueue(LinkQueue& Q)
58 {
59 Q.front = (QueuePtr)malloc(sizeof(QNode));
60 Q.front->next = NULL;
61 if (!Q.front)
62 {
63 return ERROR;
64 }
65 Q.rear = Q.front;
66 return OK;
67 }
68 Status GetHead(LinkQueue Q, QElemType& e)
69 {
70 if (Q.front==Q.rear)
71 {
72 return ERROR;
73 }
74 else
75 {
76 e = Q.front->next->data;
77 return OK;
78 }
79 }
80 Status EnQueue(LinkQueue& Q, QElemType e)
81 {
82 QueuePtr p;
83 p = (QueuePtr)malloc(sizeof(QNode));
84 if (!p)
85 {
86 return ERROR;
87 }
88 p->data = e;
89 p->next = NULL;
90 Q.rear->next = p;
91 Q.rear = p;
92 return OK;
93 }
94 Status DeQueue(LinkQueue& Q, QElemType& x)
95 {
96 QueuePtr p;
97 if (Q.front==Q.rear)
98 {
99 return ERROR;
100 }
101 p = Q.front->next;
102 x = p->data;
103 Q.front->next = p->next;
104 if (Q.rear==p)
105 {
106 Q.rear = Q.front;
107 }
108 free(p);
109 return OK;
110 }
111 int QueueLength(LinkQueue Q)
112 {
113 int a = 0;
114 QueuePtr q;
115 q = Q.front->next;
116 while (q)
117 {
118 a++;
119 q = q->next;
120 }
121 return a;
122 }