栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。经分析,C++实现堆栈,程序应实现入栈、出栈、判断栈的状态(主要是判断栈是否为空,是否为满)、获取栈顶元素、求栈的长度、清空栈中元素、输出栈中元素、销毁栈这八大功能。于是,写了一个利用数组实现这些功能的简单的程序。
#include<iostream>
using namespace std;
const int maxsize=5;
class Stack
{
public:
Stack() //构造函数,定义一个空栈
{
a=new int[maxsize];
top=0;
}
~Stack(){} //析构函数
void Push(int e); //入栈
void Pop(); //出栈
void GetTop(); //读栈顶元素
int StackSize(); //求栈长
void ClearStack(Stack s); //清空栈
bool IsEmpty(); //判断栈是否为空
bool IsFull(); //判断栈是否为满
bool Destroy(); //销毁栈
void Print(); //输出栈中元素
private:
int *a;
int top;
};
void Stack::Push(int e)
{
if(!IsFull())
{
a[top++]=e;
}
else
cout<<"栈已满,"<<e<<"未入栈!"<<endl;
}
void Stack::Pop()
{
if(!IsEmpty())
{
top--;
}
else
cout<<"栈为空!"<<endl;
}
void Stack::GetTop()
{
cout<<"栈顶元素为:"<<a[top-1]<<endl;
}
int Stack::StackSize()
{
return top;
}
void Stack::ClearStack(Stack s)
{
while(top!=0)
{
s.Pop();
top--;
}
}
bool Stack::IsEmpty()
{
if(top==0)
return true;
else
return false;
}
bool Stack::IsFull()
{
if(top>=maxsize)
return true;
else
return false;
}
bool Stack::Destroy()
{
delete this;
return true;
}
void Stack::Print()
{
if(!IsEmpty())
{
int i=top-1;
cout<<"栈内元素为:";
while(i>=0)
{
cout<<a[i]<<" ";
i--;
}
cout<<endl;
}
else
cout<<"栈为空!"<<endl;
}
void function(Stack S)
{
int n,e,i,j,k=1;
while(k){
cout<<"Please choose one function\n1:入栈\n2:求栈长\n3:读栈顶元素\n4:出栈\n5:判空\n6:判满\n7:输出栈\n8:将栈清空\n9:销毁栈\n10:退出"<<endl;
cin>>i;
switch(i)
{
case 1:
j=0;
cout<<"Please input the number of elements less than "<<maxsize<<":"<<endl;
cin>>n;
if(n>maxsize)
{
cout<<"error,please input again:"<<endl;
cin>>n;
}
while(j<n)
{
cout<<"Please input new element:"<<endl;
cin>>e;
S.Push(e);
j++;
}
break;
case 2:
cout<<"栈的长度为:"<<S.StackSize()<<endl;
break;
case 3:
S.GetTop();
break;
case 4:
S.Pop();
cout<<"已出栈!"<<endl;
break;
case 5:
if(S.IsEmpty())
cout<<"该栈为空!"<<endl;
else
cout<<"该栈不空!"<<endl;
break;
case 6:
if(S.IsFull())
cout<<"该栈已满!"<<endl;
else
cout<<"该栈未满!"<<endl;
break;
case 7:
S.Print();
break;
case 8:
S.ClearStack(S);
cout<<"已清空!"<<endl;
break;
case 9:
cout<<"栈已销毁!"<<endl;
case 10:
k=0;
break;
}
}
}
int main()
{
Stack St;
function(St);
return 0;
}