#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define STACK_SIZE 100
#define ADD_SIZE 10
typedef struct SqStack
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
bool Isempty(SqStack *s); //栈是否为空
bool IsFull(SqStack *s); //判栈是否已满
void InitStack(SqStack *s); //初始化栈
void PushStack(SqStack *s,ElemType x); //入栈
void PopStack(SqStack *s,ElemType *x); //出栈
void ShowStack(SqStack *s); //显示栈
void GetTop(SqStack *s,ElemType *x);//获取栈顶数据
void ClearStack(SqStack *s); //清理栈
void DestoryStack(SqStack *s); //摧毁栈
void Show(); //显示菜单2:功能实现文件SqStack.cpp#include"SqStack.h"
void Show()
{
printf("***************************************\n");
printf("* [1]:入栈 [2]:出栈 *\n");
printf("* [3]:显示栈 [4]:获取栈顶数据*\n");
printf("* [5]:摧毁栈 [6]:清理栈 *\n");
printf("* [0]:结束程序 *\n");
printf("***************************************\n");
printf("请选择:");
}
void InitStack(SqStack *s)
{
s->base=(ElemType*)malloc(STACK_SIZE*sizeof(ElemType));
if(s->base==NULL)
{
printf("开辟空间失败\n");
return ;
}
s->top=s->base;
s->stacksize=STACK_SIZE;
}
bool IsFull(SqStack *s)
{
return s->top-s->base>=s->stacksize;
}
bool Isempty(SqStack *s)
{
return s->base==s->top;
}
void PushStack(SqStack *s,ElemType x)
{
if(IsFull(s))
{
s->base=(ElemType*)realloc(s->base,(s->stacksize+ADD_SIZE)*sizeof(ElemType));
if(s->base==NULL)
{
printf("增加空间失败\n");
return;
}
s->top=s->base+s->stacksize;
s->stacksize+=ADD_SIZE;
}
*s->top=x;
s->top++;
}
void PopStack(SqStack *s,ElemType *x)
{
if(Isempty(s))
{
printf("栈为空,不能出栈\n");
return;
}
s->top--;
*x=*s->top;
}
void GetTop(SqStack *s,ElemType *x)
{
if(Isempty(s))
{
printf("栈为空,不能获取栈数据\n");
return;
}
*x=*(s->top-1);
}
void ClearStack(SqStack *s)
{
s->base=s->top=NULL;
s->stacksize=0;
}
void DestoryStack(SqStack *s)
{
free(s->base);
ClearStack(s);
}
void ShowStack(SqStack *s)
{
ElemType *top=s->top;
while(top!=s->base)
{
top--;
printf("%d ",*top);
}
printf("\n");
}3:主文件main.cpp#include"SqStack.h"
void main()
{
SqStack s;
ElemType x;
int pos=1;
InitStack(&s);
while(pos)
{
Show();
scanf("%d",&pos);
switch(pos)
{
case 1:
printf("输入数据,以-1结束:");
while(scanf("%d",&x),x!=-1)
{
PushStack(&s,x);
}
break;
case 2:
PopStack(&s,&x);
printf("出栈数据:%d\n",x);
break;
case 3:
ShowStack(&s);
break;
case 4:
GetTop(&s,&x);
printf("获取栈顶数据:%d\n",x);
break;
case 5:
DestoryStack(&s);
printf("栈已被摧毁\n");
break;
case 6:
ClearStack(&s);
printf("栈已被清理\n");
break;
default:
break;
case 0: return;
}
}
}原文地址:http://blog.csdn.net/zhou753099943/article/details/45787911