数据结构与算法C语言实现——栈的基本操作
雨中漫步
问题:编写程序任意输入栈长度和栈中的元素值,构造一个顺序栈,对其进行清空、销毁、入栈、出栈以及取栈顶元素操作。
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top; //栈指针
} SqStack; //顺序栈类型
void InitStack(SqStack *&s) //清空,初始化
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
void DestroyStack(SqStack *&s) //销毁
{
free(s);
}
bool Push(SqStack *&s,ElemType e) //入栈
{
if (s->top==MaxSize-1) //栈满的情况,即栈上溢出
return false;
s->top++;
s->data[s->top]=e;
return true;
}
bool Pop(SqStack *&s,ElemType &e)
{
if (s->top==-1) //栈为空的情况,即栈下溢出
return false;
e=s->data[s->top];
s->top--;
return true;
}
bool GetTop(SqStack *s,ElemType &e)
{
if (s->top==-1) //栈为空的情况,即栈下溢出
return false;
e=s->data[s->top];
return true;
}
int main()
{
SqStack *s;
InitStack(s);
int L,e,a,n;
printf("请输入栈长和栈的元素值\n");
scanf("%d",&L);
while(L--)
{
scanf("%d",&e);
Push(s,e);
}
n=20;
while(n--)
{
printf("清空请按1,销毁请按2,进栈请按3,出栈请按4,取栈顶元素请按5,结束请按6\n");
scanf("%d",&a);
if(a==1)
{
InitStack(s);
printf("清空成功!\n");
}
if(a==2)
{
DestroyStack(s);
printf("销毁成功!\n");
}
if(a==3)
{
printf("请输入进栈元素\n");
scanf("%d",&e);
if(Push(s,e))
printf("进栈成功!\n");
}
if(a==4)
{
if(Pop(s,e))
printf("出栈成功!\n");
}
if(a==5)
{
if(GetTop(s,e))
printf("成功!取出元素为:%d\n",e);
}
if(a==6)
{
break;
}
}
}