您的位置:首页 > 编程语言 > C语言/C++

通用堆栈c语言版本(可以适应任何类型)

2016-04-27 14:12 351 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define OK 0;
#define ERROR -1
#define OVERFLOW -2
#define YES 1
#define NO 0

#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10

typedef int Status;
typedef int TElemType;
typedef BiTreeLk SElemType;

typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;

//初始化栈
Status InitStack(SqStack &S)
{
S.base = (SElemType *)malloc(sizeof(SElemType)*STACK_INIT_SIZE);
if(!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}

//得到栈顶元素
Status GetTop(SqStack &S,SElemType &e)
{
if(S.top==S.base)
return ERROR;
e = *(S.top-1);
return OK;
}

//压栈
Status Push(SqStack &S,SElemType e)
{
if(S.top-S.base>=S.stacksize)
{
S.base= (SElemType *)realloc(S.base, sizeof(SElemType)*(S.stacksize+STACK_INCREMENT));
if(!S.base)
return ERROR;
S.top = S.base+S.stacksize;
S.stacksize += STACK_INCREMENT;
}
*S.top++ = e;
return OK;
}

//出栈
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base)
return ERROR;
S.top--;
e = *S.top;	return OK;
}

Status StackEmpty(SqStack &S)
{
if(S.base == S.top)
return YES;
return NO;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: