循环队列的实现(C++语言)


// Circular_Queue.cpp : Defines the entry point for the console application.
//

//#include "stdafx.h"
#include 
typedef int ElemType;

using namespace std;

const int SIZE=6;

class Circular_Queue
{
	ElemType* elem;
	int front;
	int rear;

public:
	Circular_Queue()
	{
		elem=(ElemType*)new ElemType(SIZE);
		front=0;
		rear=0;
	}
	
	~Circular_Queue()
	{
		delete[] elem;
		front=0;
		rear=0;
	}

	bool IsEmpty()
	{
		if(front==rear)
			return true;
		else
			return false;
	}
	
	bool IsFull()
	{
		if(((rear+1)%SIZE)==front)
			return true;
		else
		{
			//cout << "" << endl;
			return false;
		}
	}

	void show()
	{
		int i=front;
		cout << "现在队列中的元素是:";
		while(i!=rear)
		{
			cout << *(elem+i) << ' '; 
			i=(i+1)%SIZE;
		}
		cout << endl;
		return;
	}

	bool EnQueue(ElemType newElem)
	{
		if(IsFull())
		{
			cout << "队列已满,入队失败!\n";
			return false;
		}
		else
		{
			*(elem+rear)=newElem;
			rear=(rear+1)%SIZE;
			return true;
		}
	}

	bool DeQueue(ElemType& e)
	{
		if(IsEmpty())
		{
			cout << "队列为空,出队失败!\n";
			return false;
		} 
		else
		{
			e=*(elem+front);
			front=(front+1)%SIZE;
			return true;
		}
	}
};


int main()
{
	Circular_Queue* cir_que=new Circular_Queue();
	cir_que->show();
	cir_que->EnQueue(1);
	cir_que->show();
	cir_que->EnQueue(2);
	cir_que->show();
	cir_que->EnQueue(3);
	cir_que->show();
	cir_que->EnQueue(4);
	cir_que->show();
	cir_que->EnQueue(5);
	cir_que->show();
	cir_que->EnQueue(6);
	cir_que->show();
	cir_que->EnQueue(7);
	cir_que->show();
	ElemType el;
	cir_que->DeQueue(el);
	cout << "您出队的元素是:" << el << endl;
	cir_que->show();
	cir_que->EnQueue(7);
	cir_que->show();
	cir_que->DeQueue(el);
	cout << "您出队的元素是:" << el << endl;
	cir_que->show();
	cir_que->EnQueue(99);
	cir_que->show();
	cir_que->EnQueue(100);
	cir_que->show();
	system("pause");
	return 0;
}


你可能感兴趣的:(C&C++)