双端队列 ADT接口 数组实现

Deque ADT接口 DEQUEUE.h:

 1 #include <stdlib.h>
 2 #include "Item.h"
 3 
 4 void DEQUEUEinit(int);
 5 void DEQUEUEerror(void);
 6 Item DEQUEUEheadget(void);
 7 Item DEQUEUEtailget(void);
 8 void DEQUEUEheadput(Item);
 9 void DEQUEUEtailput(Item);
10 int DEQUEUEisEmpty(void);
11 int DEQUEUEisFull(void);

Deque ADT接口实现 DEQUEUE.c:

 1 #include "DEQUEUE.h"
 2 
 3 static Item *q;
 4 static int N,head,tail;
 5 
 6 void DEQUEUEinit(int maxN)
 7 {
 8     q=malloc(maxN*sizeof(Item));
 9     if(q==NULL)
10         DEQUEUEerror();
11     head=0;
12     tail=0;
13     N=maxN;
14 }
15 void DEQUEUEerror(void)
16 {
17     printf("\n空间可能已满或为空");
18     exit(1);
19 }
20 Item DEQUEUEheadget(void)
21 {
22     if(DEQUEUEisEmpty())
23         DEQUEUEerror();
24     Item temp=q[head];
25     head=(head+1)%N;
26     return temp;
27 }
28 Item DEQUEUEtailget(void)
29 {
30     if(DEQUEUEisEmpty())
31         DEQUEUEerror();
32     tail=(tail-1+N)%N;
33     return q[tail];
34 }
35 void DEQUEUEheadput(Item ch)
36 {
37     if(DEQUEUEisFull())
38         DEQUEUEerror();
39     head=(head-1+N)%N;
40     q[head]=ch;
41 }
42 void DEQUEUEtailput(Item ch)
43 {
44     if(DEQUEUEisFull())
45         DEQUEUEerror();
46     q[tail]=ch;
47     tail=(tail+1)%N;
48 }
49 int DEQUEUEisEmpty(void)
50 {
51     if(head==tail)
52         return 1;
53     return 0;
54 }
55 int DEQUEUEisFull(void)
56 {
57     if(((tail+1)%N)==head)
58         return 1;
59     return 0;
60 }

Item.h:

1 typedef char Item;

主程序 main.c:

 1 #include <stdio.h>
 2 
 3 int main(void)
 4 {
 5     int N;
 6     
 7     printf("输入需要申请内存大小:");
 8     if(scanf("%d", &N))
 9         DEQUEUEinit(N);
10     else
11         DEQUEUEerror();
12     getchar();
13     printf("输入%d个字符",N);
14     printf("('+'从队头get '*'从队尾get '大写字母'"
15               "从队头put '小写字母'从队尾put):\n");
16               
17     while((N=getchar())!='\n')
18     {
19         switch(N)
20         {
21             case '+':
22                 putchar(DEQUEUEheadget());
23                 break;
24             case '*':
25                 putchar(DEQUEUEtailget());
26                 break;
27             default:
28                 if(N>64&&N<91)
29                     DEQUEUEheadput(N);
30                 else
31                     DEQUEUEtailput(N);
32         }
33     }
34     
35     return 0;
36 }

 

posted on 2018-05-02 21:26  MACHINE_001  阅读(323)  评论(0编辑  收藏  举报

导航