#include <iostream>
using namespace std;
#define MaxSize 7
typedef char ElemType;
//定义栈
typedef struct
{
ElemType data[MaxSize];
int top; //栈顶指针
}SqStack;
//初始化栈
void InitStacks(SqStack *&s)
{
s=new SqStack();
s->top=-1;
}
//返回栈的长度
int StackLength(SqStack *&s)
{
return s->top;
}
//销毁栈
void DestroyStack(SqStack *&s)
{
delete s;
s=NULL;
}
//判断栈是否为空
bool StaticEmpty(SqStack *s)
{
if(s->top==-1)
{
return true;
}
else
return false;
}
//进栈
bool Push(SqStack *&s,ElemType e)
{
//栈为满,上溢出
if(s->top==MaxSize-1){
cout<<"栈上溢出!"<<endl;
return false;
}
//栈顶的元素加 1
s->top++;
//元素e放在栈顶处
s->data[s->top]=e;
return true;
}
//出栈
bool Pop(SqStack *&s,ElemType &e)
{
//栈为空的情况下,即是栈的下溢出
if(s->top==-1)
{
cout<<"栈下溢出!"<<endl;
return false;
}
e=s->data[s->top];
//栈内的元素要- -
s->top--;
return true;
}
//取栈顶元素
bool GetTop(SqStack *&s , ElemType &e)
{
//栈为空的情况下,即是栈的下溢出
if (s->top==-1){
cout<<"栈下溢出!"<<endl;
return false;
}
//取出元素
e=s->data[s->top];
return true;
}
int main()
{
ElemType e;
SqStack *s;
cout<<"栈的基本操作为:"<<endl;
InitStacks(s);
cout<<"初始化栈成功!"<<endl;
cout<<(StaticEmpty(s))?"空":"非空";
cout<<"依次进栈元素为1,2,3,4,5,6,a,b:"<<endl;
Push(s,'1');
Push(s,'2');
Push(s,'3');
Push(s,'4');
Push(s,'5');
Push(s,'6');
Push(s,'a');
Push(s,'b');
cout<<"栈的长度为:"<<StackLength(s)+1<<endl;
cout<<"出栈元素: "<<endl;
while (!StaticEmpty(s))
{
{
Pop(s,e);
cout<<e<<" ";
}
}
cout<<endl;
GetTop(s,e);
cout<<"栈顶的元素为:"<<e<<endl;
cout<<"销毁栈:"<<endl;
DestroyStack(s);
cout<<"栈销毁成功!"<<endl;
return 0;
}
出出结果:
心得体会:
栈的应用有许多的陷阱,刚开始的时候到处出错,慢慢的改正就有了成就感!