Deque ADT接口 DEQUEUE.h:spa
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:code
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:blog
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 }