实验三 链栈(c++)

来源:互联网 发布:软件源代码查看器 编辑:程序博客网 时间:2024/06/05 04:36

一、实验目的

1、 熟练掌栈和队列的结构特点,掌握栈和队列的顺序存储和链式存储结构和实现。

2、 学会使用栈和队列解决实际问题。

二、实验内容


1、 自己确定结点的具体数据类型和问题规模:

    建立一个链栈,实现栈的压栈和出栈操作。


#include<iostream>using namespace std;const int StackSize=30;template <class Datatype>class SeqStack{public:SeqStack(){top=-1;}~SeqStack(){}void Push(Datatype x);Datatype Pop();Datatype Get(){if(top!=-1) return data[top];}int Empty(){if(top==-1) return 1;else  return 0;}private:Datatype data[StackSize];int top;};
template<class Datatype>void SeqStack<Datatype>::Push(Datatype x){if(top==StackSize-1) throw"上溢";data[++top]=x;}template <class Datatype>Datatype SeqStack<Datatype>::Pop(){Datatype x;if(top==-1)throw"下溢";x=data[top--];return x;}
int main(){ SeqStack<int> S; if(S.Empty())          cout<<"栈为空!"<<endl;      else          cout<<"栈非空!"<<endl;  cout<<"构造一个空栈!"<<endl; cout<<"将5和4进行入栈操作!"<<endl;S.Push(5);S.Push (4);cout<<"栈顶元素为:";cout<<S.Get();cout<<endl;cout<<"进行第一次出栈操作!"<<endl;S.Pop();cout<<"栈顶元素为:";cout<<S.Get();cout<<endl;}


执行结果: