数据结构-C语言实现-顺序存储结构的队列

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <ctype.h>
 4 #include <string.h>
 5 typedef int ElemType;
 6 typedef struct Queue{
 7   ElemType *items;//数据项
 8   int rear;//队尾,删除
 9   int front;//队头,插入
10 }Queue;
11 
12 Queue * initQueue(){//初始化
13   Queue * Queues=(Queue *)malloc(sizeof(Queue));
14   Queues->items=(ElemType *)malloc(sizeof(ElemType)*10);//分配可存储10个数据项的空间
15   Queues->rear=0;//初始化允许插入的下标
16   Queues->front=-1;//初始化允许删除的下标
17   return Queues;
18 }
19 void delete(Queue * Queues){
20   if(Queues->front==-1||Queues->front==Queues->rear){//如果队头为-1(尚无数据项)或队头等于队尾(已无数据项)
21     printf("队列为空!\n");
22     return;
23   }
24   printf("%d已删除!\n",Queues->items[Queues->front]);
25   Queues->front++;//设为上一个队头的下一个数据项的下标
26 }
27 void insert(Queue * Queues){
28   printf("输入你想添加的整数:\n");
29   ElemType a;
30   scanf("%d",&a);
31   Queues->items[Queues->rear]=a;//队尾插入
32   if(Queues->front==-1)//如果尚无数据项
33   Queues->front=0;//队头指向第一个数据项的下标
34   Queues->rear++;//队尾指向下一个空的数据项下标
35 }
36 void display(Queue * Queues){
37   if(Queues->front==-1||Queues->front==Queues->rear){//如果队头为-1(尚无数据项)或队头等于队尾(已无数据项)
38   printf("无数据项!\n");
39   return;
40   }
41   int a=Queues->front;//获取队头下标
42   while(a<=Queues->rear){//循环至队尾
43     printf("第%d项数据:%d\n",a+1,Queues->items[a]);
44     a++;
45   }
46 }
47 void menu(){
48   printf("键入以下选项以操作,ctrl+z退出\nA:插入数据\nB:删除数据\nC:打印数据\n");
49 }
50 void main(){
51   Queue *Queues=initQueue();
52   menu();
53   char ch;
54   while((ch=getchar())!=EOF){
55     setbuf(stdin,NULL);//清空缓冲区
56     switch (toupper(ch)){
57       case 'A': insert(Queues);break;
58       case 'B': delete(Queues);break;
59       case 'C': display(Queues);break;
60     }
61   menu();
62   setbuf(stdin,NULL);//清空缓冲区
63   }
64 }

 

posted @ 2020-05-22 20:14  四字又名  阅读(244)  评论(0)    收藏  举报