实验4:栈和队列的基本操作实现及其应用2

来源:互联网 发布:淘宝卖家店铺被冻结 编辑:程序博客网 时间:2024/06/03 18:24
一、实验目的
1、 熟练掌栈和队列的结构特点,掌握栈和队列的顺序存储和链式存储结构和实现。
2、 学会使用栈和队列解决实际问题。

二、实验内容
1、 自己确定结点的具体数据类型和问题规模:
分别建立一个顺序栈和链栈,实现栈的压栈和出栈操作。

三、源程序

#include<iostream>using namespace std;const int Maxsize=100;template<class T>struct Node{T data;Node<T>*next;};template<class T>class SeqStack{public:SeqStack();void Push(T x);T Pop();T GetTop();void Dec(T x,int r);int Empty();private:Node<T>*top;};template<class T>SeqStack<T>::SeqStack(){top=NULL;}template<class T>void SeqStack<T>::Push(T x){Node<T>*s=NULL;s=new Node<T>;s->data=x;s->next=top;top=s;}template<class T>T SeqStack<T>::Pop(){T x;if(top==NULL)throw"下溢";x=top->data;Node<T>*p=top;top=top->next;delete p;return x;}template<class T>T SeqStack<T>::GetTop(){if(top!=NULL)return top->data;}template<class T>int SeqStack<T>::Empty(){if(top==NULL)return 1;else return 0;}int main(){    int n,i,j,k; SeqStack<int> S;if(S.Empty())cout<<"栈为空"<<endl;elsecout<<"栈非空"<<endl;cout<<"输入要入栈的个数:";cin>>n; cout<<"对数据执行入栈"<<endl;for(i=0;i<n;i++){int t;cout<<"输入数据:";cin>>t;S.Push(t);}cout<<"栈顶元素为:"; cout<<S.GetTop()<<endl;cout<<"输入要出栈的个数:";cin>>j; cout<<"执行出栈:"<<endl;for(k=0;k<j;k++){S.Pop(); }cout<<"栈顶元素为:"; cout<<S.GetTop()<<endl;return 0;}
四、实验结果

阅读全文
0 0