下面的这个东东是我用C宏写的,在DEV C++4.9.9.0下编译通过.
这个是头文件"stack.h"
Code:
#ifndef AVALON_STACK_H
#define AVALON_STACK_H
#include <stdio.h>
#include <string.h>
#include <assert.h>
#ifndef AVALON_BOOL
#define AVALON_BOOL
#define TRUE 1
#define FALSE 0
typedef int BOOL;/*自定义的BOOL型*/
#endif
/*定义一个栈结构*/
#define DECLARE_NODE(type,name) \
typedef struct type##NODE\
{\
type data;\
struct type##NODE *prior;\
}NODE##name;
#define DECLARE_STACK(type,name) \
struct type##STACK\
{\
int size;\
struct type##NODE *base;\
struct type##NODE *top;\
}STACK##name;
/*泛类型栈定义*/
#define DECLARE(type,name) \
DECLARE_NODE(type,name); \
DECLARE_STACK(type,name);
/****************************************************/
/*初始化栈,name为新声明的栈名字的地址 */
#define INIT(name) \
do{\
STACK##name.base=STACK##name.top=NULL;\
STACK##name.size=0;\
}while(0)
/*********** 不破坏栈顶元素取值*************************/
#define GET(name,elem) \
do{\
if(STACK##name.size != 0){\
elem=STACK##name.top->data; \
}\
}while(0)
/************** 压入元素elem **************************/
#define PUSH(name,elem) \
do{\
NODE##name *temp=(NODE##name *)malloc(sizeof(NODE##name));\
assert(temp);\
temp->data=elem ;\
(STACK##name.size)++; \
if(1 != STACK##name.size ){ \
temp->prior=STACK##name.top;\
STACK##name.top=temp;\
}\
else{\
temp->prior=NULL;\
STACK##name.top=STACK##name.base=temp;\
}\
}while(0)
/********** 栈顶元素赋值给elem,并弹出 ***********/
#define POP(name,elem) \
do{\
NODE##name * temp=STACK##name.top;\
if(STACK##name.size !=0 ){ \
*elem =STACK##name.top->data; \
if( STACK##name.size !=1){ \
STACK##name.top =temp->prior; \
free(temp);\
}\
else \
STACK##name.top=STACK##name.base=NULL;\
(STACK##name.size)--;\
}\
}while(0)
/************** 清空栈 ************************/
#define CLEAR(name) \
do{\
NODE##name * temp;\
while( STACK##name.size-- !=0){\
temp=STACK##name.top;\
STACK##name.top=STACK##name.top->prior;\
free(temp);\
}\
STACK##name.size=0;\
STACK##name.base=STACK##name.top=NULL;\
}while(0)
/****************栈空???? ************************/
#define EMPTY(name) ( STACK##name.size == 0 )
/*****************长度 ************************/
#define LENGTH(name) STACK##name.size
#endif
这个是测试程序:
Code:
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
DECLARE(int,A);
DECLARE(double,B);
double b;
int a;
INIT(A);
INIT(B);
printf("%d ",LENGTH(A));
for(a=1;a<=10000 ;a++){
PUSH(A,a);
PUSH(A,a);
PUSH(A,a);
}
printf("%d ",LENGTH(A));
for(b=1;b<=10000;b++){
PUSH(B,b);
}
while( ! EMPTY(A)){
POP(A,&a);
if( ! EMPTY(B)){
POP(B,&b);
}
}
CLEAR(A);
system("PAUSE");
return 0;
}