宏定义模板 zz

用C宏写的泛型栈

下面的这个东东是我用C宏写的,在DEV C++4.9.9.0下编译通过.
这个是头文件"stack.h"

======================================================================
#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) (1 ? STACK##name.size : 0)
#endif



这个是测试程序:
======================================================================= 
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值