文章目錄
隊列實際上是一個受限的線性表.所以可以利用單鏈表一部分功能來實現.
單鏈表的定義見:http://blog.csdn.net/weiwenhp/article/details/8634469
1.隊列的鏈表表示
#include
"LinkList.h"
template<class T>
class LinkQueue
{
private:
LinkList<T> m_pList;
public:
void EnQue(T val){m_pList.Add(val);} //入棧
T GetRear(){return m_pList.GetTailVal();} //返回棧尾元素值
T DeQue(){ //出棧
T val = m_pList.GetHeadVal();
m_pList.RemoveAt(0);
return val;
}
T GetFront(){return m_pList.GetHeadVal();} //返回棧頭部元素值
int Size(){
return m_pList.Size();}
void Clear() { m_pList.Clear(); }
};
2.隊列的數組表示
一般用數組表示隊列時,為了充分利用空間,採用所謂的迴圈隊列表示.數組邏輯上變得是首尾相連了.
假設列隊頭部指標為front,尾指標為rear.當數組全部容量用來裝隊列元素時,由於數組滿的時候和空的時候都是front==rear,為了區分隊列是滿還是空有兩種方法.
1.使用一個額外的變數size來表示元素個數,但元素個數等於數組容量maxSize時表示滿了
2.不使用額外變數,而是讓元素總個數比數組容量小1,這樣當隊列頭指標等於尾指標時表示為空白,兩者相減為1時表示滿了.
根據方法1實現的隊列
#include <iostream>
using namespace std;
const static
int QUE_SIZE = 100;
template<class T>
class QueArray
{
private:
T* m_pArray; //表示隊列的數組
int m_nSize; //當前元素個數
int m_nMaxSize; //數組可容納最大元素數量
int front; //隊頭部
int rear; //隊列尾部
public:
QueArray(int nMaxSize = QUE_SIZE){
m_nMaxSize = nMaxSize;
m_pArray = new T[m_nMaxSize];
m_nSize = front = rear = 0;
}
~QueArray(void){
delete []m_pArray;}
bool IsFull(){
return m_nSize > m_nMaxSize
;}
bool IsEmpty(){
return m_nSize ==0;}
int Size(){
return m_nSize;}
void Clear() { m_nSize = front = rear = 0; }
bool EnQue(T val){ //隊列尾部添加元素
if(IsFull()){
cout<<"queue is full."<<endl;
return
false;
}
m_pArray[rear] = val;
rear = (rear + 1) % m_nMaxSize;
m_nSize++;
}
T GetRear() { //返回隊列尾部元素
if(IsEmpty()){
cout<<"queue is empty"<<endl;
return NULL;
}
return m_pArray[rear -1];
}
T DeQue(){ //返回隊列頭部元素並刪除
if(IsEmpty()){
cout<<"queue is empty"<<endl;
return NULL;
}
T val = m_pArray[front];
front = (front + 1) % m_nMaxSize;
m_nSize --;
return val;
}
T GetFront(){ //返回頭部元素
if(IsEmpty()){
cout<<"queue is empty"<<endl;
return NULL;
}
return m_pArray[front];
}
};
根據方法2實現的隊列
#include <iostream>
using namespace std;
const static
int QUE_SIZE = 100;
template<class T>
class QueArray
{
private:
T* m_pArray; //隊列數組
int m_nMaxSize; //可容納最大元素個數
int front; //頭部元素
int rear; //尾部元素
public:
QueArray(int nMaxSize = QUE_SIZE){
m_nMaxSize = nMaxSize;
m_pArray = new T[m_nMaxSize + 1]; //數組元素比最大容量大1
front = rear = 0;
}
~QueArray(void){
delete []m_pArray;}
bool IsFull(){
return (rear+1)%m_nMaxSize == front;}
bool IsEmpty(){
return front == rear;}
int Size(){
return m_nSize;}
void Clear() { m_nSize = front = rear = 0; }
bool EnQue(T val){
if(IsFull()){
cout<<"queue is full."<<endl;
return
false;
}
m_pArray[rear] = val;
rear = (rear + 1) % m_nMaxSize;
}
T GetRear() {
if(IsEmpty()){
cout<<"queue is empty"<<endl;
return NULL;
}
return m_pArray[rear -1];
}
T DeQue(){
if(IsEmpty()){
cout<<"queue is empty"<<endl;
return NULL;
}
T val = m_pArray[front];
front = (front + 1) % m_nMaxSize;
return val;
}
T GetFront(){
if(IsEmpty()){
cout<<"queue is empty"<<endl;
return NULL;
}
return m_pArray[front];
}
};