兩個隊列模擬一個棧

思路就是兩個隊列切換來切換去。

個人代碼如下:

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

class CStack
{
public:
	void pop();
	int top();
	void push(int elem);
	void Move(queue<int> &des, queue<int> &sour, int begin, int end);
	CStack(){Loop = 0;}
	size_t size();
private:
	int Loop;
	queue<int> a[2];
};

size_t CStack::size() { return a[Loop].size(); }
void CStack::push(int elem) { a[Loop].push(elem); }
void CStack::Move(queue<int> &des, queue<int> &sour, int begin, int end)
{
	for(int i = begin; i <= end; ++i)
	{
		des.push(sour.front());
		sour.pop();
	}
}

int CStack::top()
{
	int Des = (Loop + 1) % 2;
	Move(a[Des], a[Loop], 0, a[Loop].size()-2);
	return a[Loop].front();
}

void CStack::pop()
{
	a[Loop].pop();
	Loop = (Loop + 1) % 2;
}

int main(int argc, char* argv[])
{
	CStack st;
	st.push(1);
	st.push(2);
	st.push(3);
	st.push(4);
	st.push(5);

	int size = st.size();
	//for(int i = 0; i < st.size(); ++i) //i < st.size() 這種寫法是有問題的,想想爲什麼
	for(int i = 0; i < size; ++i)
	{
		cout<< st.top();
		st.pop();
	}
	return 0;;
}

輸出:


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