刚敲了个栈的动态顺序存储的代码,跟大家交流交流,分享分享。
#define OK 1#define ERROR -1
#define STACK_MAX_SIZE 100
#define increment 50
#include"stdio.h"
#include"stdlib.h"
typedef int ElemType;
typedef int status;
typedef struct Stack_node
{
ElemType *bottom;
ElemType *top;
int stack_size;
}stack_node;
status init_stack(stack_node *S)
{
S->bottom=(ElemType*)malloc(STACK_MAX_SIZE*sizeof(ElemType));
if(S->bottom==NULL)
return ERROR;
else
{
S->top=S->bottom;
S->stack_size=STACK_MAX_SIZE;
return OK;
}
}
status push(stack_node *S,int e)
{ int *p;
if(S->top-S->bottom>=STACK_MAX_SIZE)
{
p=(ElemType*)realloc(S->bottom,(STACK_MAX_SIZE+increment)*sizeof(ElemType));
if(p==NULL)
return ERROR;
else
{ S->bottom=p;
S->top=S->bottom+S->stack_size;
S->stack_size+=increment;
*S->top=e;
S->top++;
return OK;
}
}
else
{ *S->top=e;
S->top++;
return OK;
}
}
status pop(stack_node *S,int *e)
{
if(S->top==S->bottom)
return ERROR;
else
{
S->top--;
*e=*S->top;
return OK;
}
}
void main()
{
stack_node S;
int e;
int xz=1;
if(init_stack(&S)!=OK)
printf("初始化未成功!\n");
else
while(xz!=0)
{
printf("1.入栈\t2.出栈\t0.结束\n");
scanf("%d",&xz);
switch(xz)
{
case 1:
printf("请输入要入栈的数:");
scanf("%d",&e);
if(push(&S,e)==OK)
printf("入栈成功!\n");
else
printf("入栈未成功!\n");
break;
case 2:
if(pop(&S,&e)==OK)
printf("出栈的元素为:%d\n",e);
else
printf("栈已为空!\n");
break;
case 0:
printf("谢谢使用,再见!\n");
break;
default:
printf("输入有误,请重新输入!\n");
break;
}
}
}