赞
踩
队列:只允许在一段进行插入操作,而另一端进行删除操作的线性表。
空队列:不含任何数据元素的队列。
允许插入(也称入队、进队)的一端称为队尾,允许删除(也称出队)的一端成为队头。
队列的操作特性:先进先出
确定不同的队空、队满的判定条件:
方法一:附设一个存储队列中元素个数的变量num,当num=0时队空,当num=Queuesize时为队满;
方法二:修改队满条件,浪费一个元素空间,队满时数组中只有一个空闲单元。
方法三:设置标志flag,当front=rear且flag=0时为队空,当front=rear且flag=1时为队满。
队满的条件:(rear+1) mod Queuesize==front
循环队列类的声明:
- const int QueueSize=100;
- template <class T>
- class CirQueue{
- public:
- CirQueue( );
- ~ CirQueue( );
- void EnQueue(T x);
- T DeQueue( );
- T GetQueue( );
- bool Empty( ){
- if (rear==front) return true;
- return false;
- };
- private:
- T data[QueueSize];
- int front, rear;
- };

1.入队:
- template <class T>
- void CirQueue<T>::EnQueue(T x)
- {
- if ((rear+1) % QueueSize ==front) throw "上溢";
- rear=(rear+1) % QueueSize;
- data[rear]=x;
- }
2.出队:
- template <class T>
- T CirQueue<T>::DeQueue( )
- {
- if (rear==front) throw "下溢";
- front=(front+1) % QueueSize;
- return data[front];
- }
3.读队头元素:
- template <class T>
- T CirQueue<T>::GetQueue( )
- {
- if (rear==front) throw "下溢";
- i=(front+1) % QueueSize;
- return data[i];
- }
4.返回队列长度:
- template <class T>
- int CirQueue<T>::GetLength( )
- {
- if (rear==front) throw "下溢";
- len=(rear-front+ QueueSize) % QueueSize;
- return len;
- }
链队列类的声明:
- template <class T>
- class LinkQueue {
- public:
- LinkQueue();
- ~LinkQueue();
- void EnQueue(T x);
- T DeQueue();
- T GetQueue();
- bool Empty();
- private:
- Node<T> *front, *rear;
- };
1.链队列构造函数
- template <class T>
- LinkQueue<T>::LinkQueue() {
- front=new Node<T>;
- front->next=NULL;
- rear=front;
- }
2. 入队
- template <class T>
- void LinkQueue<T>::EnQueue(T x) {
- s=new Node<T>;
- s->data=x;
- s->next=NULL;
- rear->next=s;
- rear=s;
- }
3. 出队
- template <class T>
- T LinkQueue<T>::DeQueue() {
- if (rear==front) throw "下溢";
- p=front->next;
- x=p->data;
- front->next=p->next;
- delete p;
- if (front->next==NULL) rear=front;
- return x;
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。