推免複習之數據結構與算法 環形隊列

這篇寫的是環形隊列,上一篇順序隊列中也提到了,環形隊列設計的初衷就是爲了解決假溢出問題,那他是如何成爲環形的呢?換句話說,指針是怎麼從數組的後面回到前面來的呢?取餘,環形隊列的核心就是取餘。

back=(back+1)%maxSize;

front=(front+1)%maxSize;

大致上就是這兩個操作,總之,問就是取餘。

實現代碼如下所示:

(PS:main函數裏的是我自己的測試代碼,我能確定不會發生假溢出,有沒有其他bug我就沒有測試啦 :P )

#include<iostream>
#include<vector>
using namespace std;

class circularQueue
{
private:
	int maxSize;
	int size;
	int front;
	int back;
	vector<int> q;

public:
	circularQueue(int max);
	~circularQueue();
	bool enQueue(int value);
	bool deQueue();
	int getFront();
	bool isEmpty();
	bool isFull();
};
circularQueue::circularQueue(int max=100)
{
	maxSize = max;
	size = 0;
	front = 0;
	back = 0;
	q = vector<int>(max);
}
circularQueue::~circularQueue()
{
	q.clear();
}
bool circularQueue::enQueue(int value)
{
	if ((back + 1)%maxSize == front)  //隊列爲滿
	{
		return false;
	}
	else
	{
		q[back] = value;
		back = (back + 1) % maxSize;
		size++;
		return true;
	}
}
bool circularQueue::deQueue()
{
	if (front == back)  //爲空
	{
		return false;
	}
	else
	{
		front = (front + 1) % maxSize;
		size--;
		return true;
	}
}
int circularQueue::getFront()
{
	if (front == back)
	{
		return 0;
	}
	else
	{
		return q[front];
	}
}
bool circularQueue::isEmpty()
{
	if (front == back)
	{
		return true;
	}
	else
	{
		return false;
	}
}

bool circularQueue::isFull()
{
	if ((back + 1) % maxSize == front)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	circularQueue *cq = new circularQueue();
	cout << cq->isEmpty() << endl;
	for (int i = 0; i < 99; i++)
	{
		cq->enQueue(i);
	}
	cout << cq->isFull() << endl;
	for (int i = 0; i < 49; i++)
	{
		cq->deQueue();
		cout << cq->getFront() << endl;
	}
	
	for (int i= 0; i < 49; i++)
	{
		cq->enQueue(i);
	}
	for (int i = 0; i < 49; i++)
	{
		cq->deQueue();
		cout << cq->getFront() << endl;
	}
	for (int i = 0; i < 49; i++)
	{
		cq->enQueue(i);
	}
	for (int i = 0; i < 49; i++)
	{
		cq->deQueue();
		cout << cq->getFront() << endl;
	}
	system("pause");
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章