C++编程练习(5)----“实现简单的循环队列的顺序存储结构“

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

队列是一种先进先出(First In First Out)的线性表,简称FIFO。允许插入的一端称为队尾,允许删除的一端称为队头。

循环队列是一种头尾相接的顺序存储结构

具体实现代码如下:

/* SqQueue.h 头文件 */
/*循环队列,保留一个元素空间为空,用来区分队列是满还是空*/
#include<iostream>
#define OK 1
#define ERROR 0
#define MAXSIZE 20
typedef int QElemType;
typedef int Status;

class SqQueue{
public:
	SqQueue():data(),front(0),rear(0) {}
	int QueueLength() const;
	Status EnQueue(QElemType e);	/*入队列操作*/
	Status DeQueue(QElemType *e);	/*出队列操作*/
	Status ShowQueue() const;
private:	
	QElemType data[MAXSIZE];
	int front;	/*头指针*/
	int rear;	/*尾指针,若队列不空,指向队列尾元素的下一个位置*/
};

int SqQueue::QueueLength() const
{
	return (rear-front+MAXSIZE)%MAXSIZE;
}

Status SqQueue::EnQueue(QElemType e)
{
	if ((rear+1)%MAXSIZE==front)	/*判断队列满*/
		return ERROR;
	data[rear]=e;
	rear=(rear+1)%MAXSIZE;
	return OK;
}

Status SqQueue::DeQueue(QElemType *e)
{
	if(front==rear)	/*判断队列是否为空*/
		return ERROR;
	*e=data[front];
	front=(front+1)%MAXSIZE;
	return OK;
}

Status SqQueue::ShowQueue() const
{
	if(front==rear)
	{
		std::cout<<"队列为空"<<std::endl;
		return ERROR;
	}
	std::cout<<"队列从队头至队尾内容依次为:";
	for(int k=front;k!=rear;k=(k+1)%MAXSIZE)
	{
		std::cout<<data[k]<<" ";
	}
	std::cout<<std::endl;
	return OK;
}



posted @ 2014-03-26 17:02  Never say Ever  阅读(252)  评论(0编辑  收藏  举报