链队列

 1 #define _CRT_SECURE_NO_WARNINGS//不加此行,vs下会报scanf()函数错
 2 #define DataType int
 3 
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 
 7 typedef struct node
 8 {
 9     DataType data;
10     struct node* next;
11 }QNode;
12 
13 typedef struct
14 {
15     QNode* front;
16     QNode* rear;
17 }LQueue;
18 
19 int main(void)
20 {
21     int x;//入队元素
22     int number;//出队个数
23     LQueue* q = (LQueue*)calloc(1, sizeof(LQueue));//初始化
24     QNode* p = (QNode*)calloc(1,sizeof(QNode));
25     p->next = NULL;
26     q->front = p;
27     q->rear = p;
28 
29 
30     printf("请输入入队的元素:");//入队
31     scanf("%d", &x);
32     while (x != -1)
33     {
34         if ((p = (QNode*)calloc(1, sizeof(QNode))) == NULL)
35         {
36             printf("\nclear and allocation fail!");
37             return -1;
38         }
39         p->next = q->rear->next;
40         p->data = x;
41         q->rear->next = p;
42         q->rear = p;
43         scanf("%d", &x);
44     }
45 
46     printf("\n请输入出队个数:");
47     scanf("%d", &number);
48     while (number != 0)
49     {
50         if (q->front == q->rear)
51         {
52             printf("\n队空!");
53             return -1;
54         }
55         p = q->front->next;
56         q->front->next = p->next;
57         free(p);
58         if (q->front->next == NULL)//只有一个元素时,出队后队空,修改队尾指针
59         {
60             q->rear = q->front;
61         }
62         number--;
63     }
64 
65     if (q->front == q->rear)//打印
66     {
67         printf("\n空队!");
68         return -1;
69     }
70     printf("\nfront");
71     p = q->front;
72     do
73     {
74         p = p->next;
75         printf("->%d", p->data);
76     } while (p != q->rear);
77 
78     system("pause");
79     return 0;
80 }

 

posted @ 2021-12-13 22:02  吕辉  阅读(37)  评论(0)    收藏  举报