栈的C语言实现

#include<stdio.h>
#include<stdlib.h>
#define STACK_SIZE 10
#define ElemType int
typedef struct Stack
{
ElemType * top;
ElemType * base;
int stacksize;
}stack;
void InitStack(stack * s);
void Push(stack * s,int e);
void Pop(stack * s,ElemType * e);
void Show(stack * s);
void Destroy(stack * s);
void Clear(stack * s);
void StackLen(stack * s);
int main(void)
{
int i,e=2;
ElemType * elem=(ElemType *)malloc(sizeof(ElemType));
stack * s=(stack *)malloc(sizeof(stack));
InitStack(s);
printf("请输入数字:\n");
printf("1.放入栈\n2.放出栈\n3.显示栈\n4.销毁栈\n5.清除栈\n6.栈长\n7.退出\n");
scanf("%d",&i);
while(i!=7)
{
switch(i)
{
case 1:Push(s,e);break;
case 2:Pop(s,elem);break;
case 3:Show(s);break;
case 4:Destroy(s);break;
case 5:Clear(s);break;
case 6:StackLen(s);break;
case 7:break;
default:scanf("%d",i);break;
}
printf("请输入数字:\n");
    printf("1.入栈\n2.出栈\n3.显示栈\n4.销毁栈\n5.清除栈\n6.栈长\n7.退出\n");
    scanf("%d",&i);
}
return 0;
}
void InitStack(stack * s)\*创建栈*\
{
s->base=(ElemType *)malloc(sizeof(ElemType)*STACK_SIZE);
    if(!s->base)
{
exit(0);
}
s->top=s->base;
s->stacksize=STACK_SIZE;
}
void Push(stack * s,int e)\*入栈*\
{
if(s->top-s->base>=s->stacksize)
{
s->base=(ElemType *)realloc(s->base,(s->stacksize+STACK_SIZE)*sizeof(ElemType));
if(!s->base)
{
exit(0);
}
s->top=s->base+s->stacksize;
s->stacksize=s->stacksize+STACK_SIZE;
}
*(s->top)=e;
s->top++;
}
void Pop(stack * s,ElemType * e)\*出栈*\
{
if(s->top==s->base)
exit(0);
* e=*--(s->top);
}
void Show(stack * s)\*显示栈中元素*\
{
ElemType * temp=s->top;
int i=1;
while(s->top!=s->base)
{
printf("第%d个值为:%d\n",i,*(--(s->top)));
i++;
}
s->top=temp;
}
void Destroy(stack * s)\*销毁栈*\
{
free(s->base);
}
void Clear(stack * s)\*清除栈*\
{
s->top=s->base;
}
void StackLen(stack * s)\*显示栈长*\
{
int num;
num=s->top-s->base;
printf("the length of stack is %d\n",num);
}


你可能感兴趣的:(数据结构,c,栈)