泛型栈
1 #ifndef AVALON_STACK_H 2 #define AVALON_STACK_H 3 #include <stdio.h> 4 #include <string.h> 5 #include <assert.h> 6 7 #ifndef AVALON_BOOL 8 #define AVALON_BOOL 9 #define TRUE 1 10 #define FALSE 0 11 typedef int BOOL;/*自定义的BOOL型*/ 12 #endif 13 14 /*定义一个栈结构*/ 15 #define DECLARE_NODE(type,name) \ 16 typedef struct type##NODE\ 17 {\ 18 type data;\ 19 struct type##NODE *prior;\ 20 }NODE##name; 21 22 #define DECLARE_STACK(type,name) \ 23 struct type##STACK\ 24 {\ 25 int size;\ 26 struct type##NODE *base;\ 27 struct type##NODE *top;\ 28 }STACK##name; 29 30 /*泛类型栈定义*/ 31 #define DECLARE(type,name) \ 32 DECLARE_NODE(type,name); \ 33 DECLARE_STACK(type,name); 34 /***********************************************/ 35 /*初始化栈,name为新声明的栈名字的地址 */ 36 #define INIT(name) \ 37 do{\ 38 STACK##name.base=STACK##name.top=NULL;\ 39 STACK##name.size=0;\ 40 }while(0) 41 42 /*********** 不破坏栈顶元素取值*************************/ 43 #define GET(name,elem) \ 44 do{\ 45 if(STACK##name.size != 0){\ 46 elem=STACK##name.top->data; \ 47 }\ 48 }while(0) 49 50 /************** 压入元素elem **************************/ 51 #define PUSH(name,elem) \ 52 do{\ 53 NODE##name *temp=(NODE##name *)malloc(sizeof(NODE##name));\ 54 assert(temp);\ 55 temp->data=elem ;\ 56 (STACK##name.size)++; \ 57 if(1 != STACK##name.size ){ \ 58 temp->prior=STACK##name.top;\ 59 STACK##name.top=temp;\ 60 }\ 61 else{\ 62 temp->prior=NULL;\ 63 STACK##name.top=STACK##name.base=temp;\ 64 }\ 65 }while(0) 66 67 /********** 栈顶元素赋值给elem,并弹出 ***********/ 68 #define POP(name,elem) \ 69 do{\ 70 NODE##name * temp=STACK##name.top;\ 71 if(STACK##name.size !=0 ){ \ 72 *elem =STACK##name.top->data; \ 73 if( STACK##name.size !=1){ \ 74 STACK##name.top =temp->prior; \ 75 free(temp);\ 76 }\ 77 else \ 78 STACK##name.top=STACK##name.base=NULL;\ 79 (STACK##name.size)--;\ 80 }\ 81 }while(0) 82 83 /************** 清空栈 ************************/ 84 #define CLEAR(name) \ 85 do{\ 86 NODE##name * temp;\ 87 while( STACK##name.size-- !=0){\ 88 temp=STACK##name.top;\ 89 STACK##name.top=STACK##name.top->prior;\ 90 free(temp);\ 91 }\ 92 STACK##name.size=0;\ 93 STACK##name.base=STACK##name.top=NULL;\ 94 }while(0) 95 96 /****************栈空 ************************/ 97 #define EMPTY(name) ( STACK##name.size == 0 ) 98 99 /*****************长度 ************************/ 100 #define LENGTH(name) (1 ? STACK##name.size : 0) 101 #endif
测试程序
1 #include "stack.h" 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 int main(void) 6 { 7 DECLARE(int,A); 8 DECLARE(double,B); 9 double b; 10 int a; 11 INIT(A); 12 INIT(B); 13 printf("%d ",LENGTH(A)); 14 for(a=1;a<=10000 ;a++){ 15 PUSH(A,a); 16 PUSH(A,a); 17 PUSH(A,a); 18 } 19 printf("%d ",LENGTH(A)); 20 for(b=1;b<=10000;b++){ 21 PUSH(B,b); 22 } 23 while( ! EMPTY(A)){ 24 POP(A,&a); 25 if( ! EMPTY(B)){ 26 POP(B,&b); 27 } 28 } 29 CLEAR(A); 30 system("PAUSE"); 31 return 0; 32 }