栈和队列(2)

队列
队列比栈稍微复杂一点,特别是顺序存储结构中,有一个rear,一个front,要把他俩连起来,挺麻烦的,还有假溢出问题,队空队满的讨论都是比较难的地方,需要仔细推敲。
一、基本知识

队列:只允许在一端进行插入操作,而另一端进行删除操作的线性表。

允许插入(也称入队、进队)的一端称为队尾,允许删除(也称出队)的一端称为队头。

空队列:不含任何数据元素的队列。

假溢出:当元素被插入到数组中下标最大的位置上之后,队列的空间就用尽了,尽管此时数组的低端还有空闲空间,这种现象叫做假溢出。

二、队列的顺序存储结构及实现栈和队列(2)


假溢出

栈和队列(2)
**求模:**

rear=(rear+1)% MAXSIZE
 front=(front+1)% MAZSIZE

队空:front==rear

队满的条件:(rear+1)% 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;
};

循环队列的实现——入队

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( )
{   
if (rear==front) throw "下溢";    
i=(front+1) % QueueSize;     
return data[i];
}

循环队列的实现——队列长度

template <class T>
int CirQueue<T>::GetLength( )
{   
if (rear==front) throw "下溢";    
len=(rear-front+ QueueSize) % QueueSize;    
return len;
}  

三、队列的链接存储结构及实现

栈和队列(2)
链队列类的声明

template <class T>
class LinkQueue
{  
public:     
LinkQueue( );         
~LinkQueue( );      
void EnQueue(T x);     
T DeQueue( );            
T GetQueue( );     
bool Empty( ); 
private:
 Node<T> *front, *rear;
};

链队列的实现——构造函数

template <class T>
LinkQueue<T>::LinkQueue( )

front=new Node<T>;     
front->next=NULL;      
rear=front;
}

链队列的实现——入队

template <class T>
void LinkQueue<T>::EnQueue(T x)

  s=new Node<T>; 
 s->data=x; 
  s->next=NULL;   
rear->next=s;    
rear=s;
}
栈和队列(2)
链队列的实现——出队

栈和队列(2)

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;