一、实验目的
1、 熟练掌栈和队列的结构特点,掌握栈和队列的顺序存储和链式存储结构和实现。
2、 学会使用栈和队列解决实际问题。
二、实验内容
确定结点的具体数据类型和问题规模:
建立一个顺序栈,实现栈的压栈和出栈操作。
#include <iostream>
using namespace std;
const int Stacksize=10;
template <class Datatype>
class Seqstack
{
public:
Seqstack();
~Seqstack();
void Push (Datatype x);
Datatype Pop();
Datatype Gettop();
int Empty();
void Printstack();
private:
Datatype data[Stacksize];
int top;
};
template <class Datatype>
Seqstack<Datatype>::Seqstack()
{
top = -1;
}
template <class Datatype>
Seqstack<Datatype>::~Seqstack()
{
}
template <class Datatype>
void Seqstack<Datatype>::Push( Datatype x)
{
if(top == Stacksize-1) throw "上溢";
data[++top]=x;
}
template <class Datatype>
Datatype Seqstack<Datatype>:: Pop()
{
if(top==-1) throw "下溢";
top--;
return data[top];
}
template <class Datatype>
Datatype Seqstack<Datatype>::Gettop()
{
if(top!=-1) return data[top];
}
template <class Datatype>
int Seqstack<Datatype>::Empty()
{
if(top==-1) cout<<"此顺序栈为空栈";
if(top!=-1) cout<<"此顺序栈不为空栈";
return 0;
}
template <class Datatype>
void Seqstack<Datatype>::Printstack()
{
for (int i = top; i>=0; i--)
{
cout << data[i] << " ";
}
cout << endl;
}
int main()
{
Seqstack<int> a;
a.Push(1);
a.Push(2);
a.Push(3);
cout<<"栈的列表为:"<<endl;
a.Printstack();
cout<<"栈的栈顶元素为:"<<endl;
cout<<a.Gettop()<<endl;
cout<<"该栈的情况"<<endl;
cout<<a.Empty()<<endl;
a.Pop();
cout<<"出栈一个元素后,该顺序栈的顺序为:"<<endl;
a.Printstack();
return 0;
}