Deque ADT接口 DEQUEUE.h:node
1 #include <stdlib.h> 2 #include "Item.h" 3 4 typedef struct DEQUEUEnode *link; 5 struct DEQUEUEnode 6 { 7 Item item; 8 link next; 9 link last; 10 }; 11 12 void DEQUEUEinit(int); 13 void DEQUEUEerror(void); 14 Item DEQUEUEheadget(void); 15 Item DEQUEUEtailget(void); 16 void DEQUEUEheadput(Item); 17 void DEQUEUEtailput(Item); 18 int DEQUEUEisEmpty(void); 19 int DEQUEUEisFull(void);
Deque ADT接口實現 DEQUEUE.c:spa
1 static link head,tail; 2 static int N; //備用 3 4 void DEQUEUEinit(int maxN) 5 { 6 head=malloc(sizeof(*head)); 7 tail=head; 8 tail->next=NULL; 9 tail->last=NULL; 10 head->next=NULL; 11 head->last=NULL; 12 N=maxN; 13 } 14 void DEQUEUEerror(void) 15 { 16 printf("節點爲空或節點已滿"); 17 exit(1); 18 } 19 Item DEQUEUEheadget(void) 20 { 21 Item temp; 22 temp=head->item; 23 head=head->next; 24 free(head->last); 25 head->last=NULL; 26 return temp; 27 } 28 Item DEQUEUEtailget(void) 29 { 30 Item temp; 31 tail=tail->last; 32 temp=tail->item; 33 free(tail->next); 34 tail->next=NULL; 35 return temp; 36 } 37 void DEQUEUEheadput(Item value) 38 { 39 head->last=malloc(sizeof(*head)); 40 if(DEQUEUEisFull()) 41 DEQUEUEerror(); 42 head->last->next=head; 43 head=head->last; 44 head->item=value; 45 head->last=NULL; 46 } 47 void DEQUEUEtailput(Item value) 48 { 49 tail->item=value; 50 tail->next=malloc(sizeof(*head)); 51 if(DEQUEUEisFull()) 52 DEQUEUEerror(); 53 tail->next->last=tail; 54 tail=tail->next; 55 tail->next=NULL; 56 } 57 int DEQUEUEisEmpty(void) 58 { 59 if(head==NULL&&tail==NULL) 60 return 1; 61 return 0; 62 } 63 int DEQUEUEisFull(void) 64 { 65 if((head==NULL&&tail!=NULL)||(head!=NULL&&tail==NULL)) 66 return 1; 67 return 0; 68 }
Item.h:code
1 typedef char Item;
主程序 main.c:blog
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 }