您的位置:首页 > 其它

顺序栈的设计与实现

2012-12-17 23:42 232 查看
直接上代码
//2012-12-16
//顺序栈的设计与实现
//author:@quanwei

#include<stdio.h>
#include<stdlib.h>

#define STACK_INIT_SIZE 4
#define STACKINCREMENT 10

typedef struct Stack{
int *base;
int *top;
int stackSize;
}STACK;
STACK *stack = (STACK *)malloc(sizeof(STACK));

/*****************************/
//函数名:CreatStack()
//参数:无
//作用:构造一个空栈
//返回值:栈底指针
/*****************************/
int *CreatStack(){
stack->base = (int *)malloc(sizeof(int)*STACK_INIT_SIZE);
if(stack == NULL)	return 0;
stack->stackSize = STACK_INIT_SIZE -1;				//有一个空间空闲
stack->base;
stack->top = stack->base;
return stack->base;
}

/*****************************/
//函数名:PushStack(int elem)
//参数:int elem 入栈元素
//作用:elem入栈
//返回值:无
/*****************************/
void PushStack(int elem){
if(stack->top - stack->base >= stack->stackSize){				//栈满追加存储空间 
stack->base=(int *)realloc(stack->base,(stack->stackSize+STACKINCREMENT)* sizeof(int));
stack->top = stack->base + stack->stackSize;			//确定栈顶地址
stack->stackSize += STACKINCREMENT;
}
stack->top++;
*stack->top = elem;				//stack->top = &elem 是错的   why?
}

/*****************************/
//函数名:PopStack(int *top)
//参数:int *top 栈顶指针
//作用:出栈
//返回值:成功为出栈元素,失败提示错误
/*****************************/
int PopStack(int *top){
if(stack->base == stack->top){
printf("The stack is already full");
exit(0);
}
return *stack->top--;
}

/*****************************/
//函数名:GetTop()
//参数:无
//作用:取栈顶元素
//返回值:成功为栈顶元素,栈为空提示错误
/*****************************/
int GetTop(){
if(stack->base == stack->top){
printf("The stack is already full");
exit(0);
}
return *(stack->top);
}
/***********	测试程序	 ************/
void main(){
char ch = 'y';
int num;
CreatStack();
while(ch == 'y'){
printf("Input element");
scanf("%d",&num);
PushStack(num);
fflush(stdin);
printf("go on?(y/n)");
scanf("%c",&ch);
fflush(stdin);
}
printf("The top element of the stack is:%4d",GetTop());
printf("now pop stack\n");
while(stack->top != stack->base){
printf("%4d",PopStack(stack->top));
}
}
个人比较喜欢链栈
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: