//栈的实现
//供学习c++人员使用
#define STACK_SIZE 10000 //宏定义
#include<iostream> //头文件
using namespace std;
template<class elemtype>
struct node
{
elemtypedata; //数据域
node<elemtype>*next; //指针域
node(){next=NULL;} //无参数的的构造函数
node(elemtypeitem,node<elemtype>*link=NULL)//已知数据元素值和指针建立结点
{
data=item;
next=link;
}
};
template<class elemtype>
class stack
{
public:
stack(){} //构造函数
virtual~stack(){} //析构函数
virtualbool push(const elemtype &e)=0; //入栈
virtualbool pop(elemtype &e)=0; //出栈
virtualbool gettop(elemtype &e)const=0;//取栈顶元素
};
//顺序栈类模板
template<class elemtype>
class sqstack:public stack<elemtype>
{
private:
elemtypeelem[STACK_SIZE]; //存取栈元素值
int top; //栈顶
public:
sqstack(){top=-1;} //构造函数
~sqstack(){} //析构函数
boolpush(const elemtype &e) //入栈
{
if(top==STACK_SIZE-1)return false; //栈满,入栈失败
else
{ //栈未满
elem[++top]=e; //栈顶指针加1后将e入栈
return true; //入栈成功
}
}
boolpop(elemtype &e) //出栈
{
if(top==-1)return false; //栈空,出栈失败
else
{ //栈不空
e=elem[top--]; //用e返回栈顶元素后将栈顶指针减1
returntrue; //出栈成功
}
}
boolgettop(elemtype &e)const //取栈顶元素
{
if(top==-1)return false; //栈空,出栈失败
else
{ //栈不空
e=elem[top]; //用e返回栈顶元素
returntrue; //出栈成功
}
}
};
template<class elemtype>
class linkstack:public stack<elemtype>
{
private:
node<elemtype>*top; //栈顶指针
public:
linkstack(){top=NULL;} //构造函数
~linkstack() //析构函数
{
elemtypee; //临时变量
while(top!=NULL)pop(e); //出栈,直到栈为空
}
boolpush(const elemtype &e) //入栈
{
top=newnode<elemtype>(e,top); //以e为数据值,top指向下一结点构造新节点
returntrue; //入栈成功
}
boolpop(elemtype &e) //出栈
{
if(top==NULL)return false; //栈空,出栈失败
else
{ //栈不空
e=top->data; //用e返回栈顶元素
node<elemtype>*p=top; //暂存栈顶
top=top->next; //top指向下一结点
delete p; //释放原栈顶
return true; //出栈成功
}
}
boolgettop(elemtype &e)const //取栈顶元素
{
if(top==NULL)return false; //栈空,出栈失败
else
{ //栈不空
e=top->data; //用e返回栈顶元素
returntrue; //出栈成功
}
}
};
int main()
{
int select=0; //工作变量
stack<int>*pstack; //指向栈的指针
int e; //元素
do
{
cout<<"请选择(1:测试顺序栈,2:测试链式栈)";
cin>>select; //输入选择
}
while(select!=1&&select!=2);
if(select==1)
pstack=newsqstack<int>;
elsepstack=new linkstack<int>;
while(select!=5)
{
cout<<"1.生成栈"<<endl;
cout<<"2.入栈"<<endl;
cout<<"3.出栈"<<endl;
cout<<"4.取出栈顶"<<endl;
cout<<"5.退出"<<endl;
cout<<"选择功能(1~5):";
cin>>select; //输入菜单功能选项
switch(select)
{
case1: //生成栈
cout<<"输入e(e=0时退出):";
cin>>e; //输入e
while(e!=0)
{
pstack->push(e); //e非0入栈
cin>>e; //输入e
}
break;
case2: //入栈
cout<<"输入元素值:";
cin>>e; //输入e
pstack->push(e); //入栈
break;
case 3: //出栈
pstack->pop(e); //出栈操作
cout<<"栈顶元素值为"<<e<<endl; //输出栈顶元素
break;
case4: //取栈顶
pstack->gettop(e); //取栈顶操作
cout<<"栈顶元素值为"<<e<<endl; //取出栈顶元素
break;
}
}
deletepstack; //释放存取空间
system("PAUSE");
return 0;
}