顺序队列和链队列啊哦?!

来源:互联网 发布:美国经济数据发布时间 编辑:程序博客网 时间:2024/06/10 07:39


一、实验目的
1、   熟练掌队列的结构特点,掌握队列的顺序存储和链式存储结构和实现。
2、      学会使用队列解决实际问题。
二、实验内容
1、自己确定结点的具体数据类型和问题规模:
分别建立一个顺序队列和链队列,实现队列的入队和出队操作。

三、实验步骤
1、依据实验内容分别说明实验程序中用到的数据类型的定义;
2、相关操作的算法表达;
3、完整程序;
4、总结、运行结果和分析。
5、总体收获和不足,疑问等。

四 顺序队列

#include<iostream>using namespace std;const int queuesize=100;template<class T>class cirqueue{public:cirqueue(){front=rear=queuesize-1;}~cirqueue(){}void enqueue (T x);T dequeue();T getqueue();int empty(){if(front==rear) { return 1; }else{  return 0;  }}private:T data[queuesize];int front,rear;};template<class T>void cirqueue<T>::enqueue(T x){if((rear+1)%queuesize==front)throw"表满,上溢";rear=(rear+1)%queuesize;data[rear]=x;}template<class T>T cirqueue<T>::dequeue(){if(rear==front)throw"表空,下溢";front=(front+1)%queuesize;return data[front];}template<class T>T cirqueue<T>::getqueue(){   int i;if(front==rear)throw"表空,下溢";i=(front+1)%queuesize;return data[i];}int main(){cirqueue<int>L;if(L.empty())cout<<"队列为空"<<endl;elsecout<<"队列不为空"<<endl;cout<<"元素20和30入队:"<<endl;try{L.enqueue(20);L.enqueue(30);}catch(char* wrong){cout<<wrong<<endl;}   cout<<"查看队头元素:"<<endl;   cout<<L.getqueue()<<endl;   cout<<"执行出队操作:"<<endl;   try   {   L.dequeue();   }   catch(char* wrong)   {    cout<<wrong<<endl;   }   cout<<"查看队头元素:"<<endl;   cout<<L.getqueue()<<endl;   return 0;}

运行的结果


五 链队列

#include<iostream>using namespace std;template<class T>struct node{T data;node<T>*next;};template<class T>class linkqueue{public:linkqueue();~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> linkqueue<T>::~linkqueue() { node<T>*p=NULL; while(front!=NULL) { p=front->next; delete front; front=p; } } 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; else  return 0; }int main(){linkqueue<int>L;if(L.empty())cout<<"队列为空"<<endl;elsecout<<"队列不为空"<<endl; cout<<"元素20和30入队:"<<endl;try{L.enqueue(20);L.enqueue(30);}catch(char* wrong){cout<<wrong<<endl;}   cout<<"查看队头元素:"<<endl;   cout<<L.getqueue()<<endl;   cout<<"执行出队操作:"<<endl;   try   {   L.dequeue();   }   catch(char* wrong)   {    cout<<wrong<<endl;   }   cout<<"查看队头元素:"<<endl;   cout<<L.getqueue()<<endl;   return 0;}

运行结果



六 实验心得

希望多练习多去改错多进步!!!!!!!




原创粉丝点击