一、队列的定义
队列是一种特殊的线性表,线性表两端都可以进行插入删除,而队列只能在队头删除,队尾插入。插入元素称为入队,删除元素称为出队。
特点:
1、队列只允许在队头插入,队尾删除;
2、先入队的元素在对头,后入队的元素在队尾;
3、队列遵循“先进先出”的原则。
图示:
(1)普通队列
(2)环形队列
二、存储结构及实现
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iostream>
#include<iomanip>
using namespace std;
class CRingQueue{
private:
int iLen;
int iSize;
int iFront;
int iRear;
int *pArr;
public:
CRingQueue(int size){//创建队列
iSize = size;
iFront = iRear = iLen = 0;
pArr = (int*)malloc(sizeof(int)*iSize);
memset(pArr, 0, sizeof(int)*iSize);
}
~CRingQueue(){free(pArr); pArr = NULL;}/*删除队列*/
//队头队尾操作
void QueueRearInc(){iRear++; iRear = iRear % iSize;}
void QueueFrontInc(){iFront++; iFront = iFront % iSize;}
bool IsEmpty(){return (iLen == 0);}/*队列判空*/
bool IsFull(){return (iLen >= iSize);}/*队列判满*/
int Size(){return iLen;}/*返回队列现有长度*/
//往队尾放入元素
bool EnQueue(int element){
if(IsFull()){
cout << "Error : OverFlow !" << endl;
return false;
}
pArr[iRear] = element; QueueRearInc(); iLen++;
return true;
}
int Front(){
if(IsEmpty()) return 0x80000000;
return pArr[iFront];
}
int Rear(){
if(IsEmpty()) return 0x7FFFFFFF;
return pArr[iRear];
}
//删除队列第一个元素
bool DeQueue(int& element){
if(IsEmpty()){
cout << "Error : UnderFlow" << endl;
return false;
}
element = pArr[iFront];
QueueFrontInc();
iLen--;
return true;
}
//打印队列中的全部元素
void Disp(){
cout << "QueueBegin>>>>>>>>>>>>>>>>>>>>>>>>>>" << endl;
if(!IsEmpty()) cout << "Head : " << Front() << ", Tail : " << Rear() << endl;
int iHead = iFront;
for(int i = 0; i < iLen; i++){
cout <<setw(4) << pArr[iHead++%iSize];
}
cout << endl << ">>>>>>>>>>>>>>>>>>>>>>>>>>>QueueEnd" << endl << endl;
}
};
void main()
{
CRingQueue oRingQueue(20);
oRingQueue.Disp();
cout << "20 elements enqueue : " << endl;
for(int i = 0; i < 25; i++){
oRingQueue.EnQueue(i+1);
}
oRingQueue.Disp();
cout << "10 elements dequeue : " << endl;
for(int i = 0; i < 10; i++){
int iTmp;
oRingQueue.DeQueue(iTmp);
}
oRingQueue.Disp();
}