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

来源:互联网 发布:淘宝开专卖店 编辑:程序博客网 时间:2024/06/05 01:14
一、实验目的
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 LinkQueue{public:LinkQueue();void EnQueue(T x);T DeQueue();T GetQueue();int Empty();private:Node<T>*front,*rear;};template<class T>LinkQueue<T>::LinkQueue(){Node<T>*s=NULL;s=new Node<T> ;s->next=NULL;front=rear=s;}template<class T>void LinkQueue<T>::EnQueue(T x){Node<T>*s=NULL;s=new Node<T>;s->data=x;s->next=NULL;rear->next=s;rear=s;}template<class T>T LinkQueue<T>::DeQueue(){Node<T>*p=NULL;int x;if(rear==front)throw"下溢";p=front->next;x=p->data;front->next=p->next;if(p->next==NULL)rear=front;delete p;return x;}template<class T>T LinkQueue<T>::GetQueue(){if(front!=rear)return front->next->data;}template<class T>int LinkQueue<T>::Empty(){if(front==rear)return 1;elsereturn 0; }int main(){int n,j;LinkQueue<int> L;if(L.Empty())cout<<"队列为空"<<endl;elsecout<<"队列非空"<<endl;cout<<"执行入队"<<endl;cout<<"入队次数:";cin>>n;for(int i=0;i<n;i++){int t;cout<<"输入入队数据:" ;cin>>t;L.EnQueue(t);}cout<<"队头元素为:"; cout<<L.GetQueue()<<endl;cout<<"执行出队:"<<endl;cout<<"出队次数:";cin>>j;for(int k=0;k<j;k++){L.DeQueue(); }cout<<"队头元素为:"; cout<<L.GetQueue()<<endl;return 0;}

四、实验结果


阅读全文
0 0