栈(stack)是一种运算受限的线性表。仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其下面元素成为新的栈顶元素。
#include<iostream>
#include<stdlib.h>
#define stack_size 100
#define add 10
using namespace std;
#define TRUE 1
#define FALSE 0
struct stack
{
int *base;
int *top;
int *t;//遍历时使用新的指针,如果依然使用S.top会影响后续使用
int size;
}S;
//初始化
int InitStack()
{
S.base=(int *)malloc(stack_size * sizeof(int));
if(!S.base) return FALSE;
else
{
S.top=S.base;
S.size=stack_size;
}
}
//销毁栈
int DestroyStack()
{
S.top=S.base;
free(S.base);
S.base=NULL;//指针指向空
S.top=NULL;
}
//置为空栈
int ClearStack()
{
S.top=S.base;
S.size=0;
return TRUE;
}
//判断是否为空栈
int EmptyStack()
{
if(S.base==NULL||S.base==S.top) return TRUE;
else return FALSE;
}
//求栈的长度
int StackLength()
{
if(EmptyStack()!=TRUE) return (S.top-S.base);
else return FALSE;
}
//求栈顶元素
int GetTop()
{
if(EmptyStack()!=TRUE) return (*(S.top-1));
else return FALSE;
}
//压入
int Push(int e)
{
if(S.top-S.base>=S.size)//空间不够
{
S.base=(int *)malloc((S.size+add)*sizeof(int));//扩展空间
if(!S.base) return FALSE;
S.top=S.base+S.size;
S.size+=add;
}
*S.top++=e;
return TRUE;
}
//弹出
int Pop(int e)
{
if(EmptyStack()==TRUE) return FALSE;
else
{
e=*(S.top--);
return TRUE;
}
}
//遍历
int Traverse()
{
S.t=S.top;
if(EmptyStack()==TRUE) return FALSE;
else
{
cout<<"Stack:";
while(S.t!=S.base)
{
cout<<*(S.t-1)<<" ";
S.t--;
}
cout<<endl;
}
return TRUE;
}
int main()
{
cout<<"*******************************"<<endl;
cout<<"* 1.DestroyStack *"<<endl;
cout<<"* 2.ClearStack *"<<endl;
cout<<"* 3.EmptyStack *"<<endl;
cout<<"* 4.StackLength *"<<endl;
cout<<"* 5.GetTop *"<<endl;
cout<<"* 6.Push *"<<endl;
cout<<"* 7.Pop *"<<endl;
cout<<"* 8.Traverse *"<<endl;
cout<<"* 9.exit *"<<endl;
cout<<"*******************************"<<endl;
int e,a1,a2;
if(InitStack()) cout<<"Initialize completely!"<<endl;
while(1)
{
cout<<"——Please choose the number and input it:"<<endl;
cin>>a1;
switch(a1)
{
case 1:
{
if(DestroyStack()) cout<<"Destroy successfully!"<<endl;
break;
}
case 2:
{
if(ClearStack()==TRUE) cout<<"Clear stack successfully!"<<endl;
break;
}
case 3:
{
if(EmptyStack()==TRUE) cout<<"the stack is empty!"<<endl;
else
{
cout<<"not empty!"<<endl;
}
break;
}
case 4:
{
if(StackLength()==TRUE) cout<<"length:"<<StackLength()<<endl;
else
{
cout<<"Error!The stack is empty."<<endl;
}
break;
}
case 5:
{
if(GetTop()!=TRUE) cout<<"the value of Top:"<<GetTop()<<endl;
else
{
cout<<"Error!The stack is empty."<<endl;
}
break;
}
case 6:
{
while(1)
{
cout<<"Input the value:";
cin>>e;
getchar();
if(Push(e)==TRUE) cout<<"Push successfully!"<<endl;
else {cout<<"Error!"<<endl;}
cout<<"Continue? input Y or N :";
a2=getchar();
if(a2!='y'&&'Y') break;
//if(gerchar()!='Y'||'y') break;
}
break;
}
case 7:
{
if(Pop(e)==TRUE)
{
cout<<"Pop successfully! the result of Pop:"<<e<<endl;
break;
}
}
case 8:
{
if(Traverse()!=TRUE) cout<<"Error!The stack is empty."<<endl;
break;
}
case 9:return 0;
}//switch
}
}