队列的基本操作实现
c++实现
#include<stdio.h>
using namespace std;
/* typedef struct QNode //c语言队列链式的定义
{
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue; */
class Queue //顺序存储实现循环队列
{
private:
int *Queue_Buffer; //Queue_Buffer[0]队头 Queue_Buffer[0]队尾
int QueueLength;
int QueueCapacity;
int Head;
int Tail;
public:
Queue(int queuecapactiy) //InitQueue(&Q)
{
QueueCapacity=queuecapactiy;
Queue_Buffer=new int[QueueCapacity];
QueueLength=0;
Head=0;
Tail=0;
}
~Queue() //DestroyQueue(&Q)
{
delete []Queue_Buffer;
Queue_Buffer=NULL;
}
void ClearQueue() //ClearQueue(&Q)
{
QueueLength=0;
Head=0;
Tail=0;
}
bool EmptyQueue() //EmptyQueue(Q)
{
if(0==QueueLength) return true;
else return false;
}
bool FullQueue()
{
if(QueueLength==QueueCapacity) return true;
else return false;
}
int GetLength() //GetLength(Q)/
{
return QueueLength; //c中链式实现 (Q.rear-Q.front+QueueCapacity )%QueueCapacity
}
bool EnQueue(int elem) //EnQueue(&Q,elem)
{
if(!FullQueue()) //c链式判满 (Q.rear+1)%QueueCapacity==Q.front
{
Queue_Buffer[Tail]=elem;
Tail++;
if(Tail>QueueCapacity) Tail=0;
/* Tail=Tail%QueueCapacity; */
QueueLength++;
return true;
}
else return false;
}
bool DeQueue(int &elem) //DeQueue(&Q,&elem)
{
if(!EmptyQueue()) //c链式判空 Q.front==Q.rear
{
elem=Queue_Buffer[Head];
Head++;
/* Head=Head%QueueCapacity; */
if(Head>QueueCapacity) Head=0;
QueueLength--;
return true;
}
else return false;
}
void QueueTraverse() //QueueTraverse(Q,visit())
{
for(int i=Head;i<QueueLength+Head;i++)
{
printf("%i ",Queue_Buffer[i%QueueCapacity]); //从队头遍历至队尾
}
printf("\n");
}
};
int main()
{
int elem=0;
Queue *queue=new Queue(5);
queue->ClearQueue();
queue->EnQueue(1);
queue->EnQueue(2);
queue->EnQueue(3);
queue->EnQueue(4);
printf("元素个数:%i\n",queue->GetLength());
printf("队列为:");
queue->QueueTraverse();
queue->DeQueue(elem);
printf("删除元素为:%i\n",elem);
queue->DeQueue(elem);
printf("删除元素为:%i\n",elem);
printf("元素个数:%i\n",queue->GetLength());
queue->QueueTraverse();
delete queue;
return 0;
}