天天看點

C++ 用兩個隊列實作一個棧

下面兩幅圖分别是棧和隊列的簡單介紹:

C++ 用兩個隊列實作一個棧

1.入棧(push)

C++ 用兩個隊列實作一個棧
入棧時,給其中一個隊列入相同的資料。

2.出棧(pop)

C++ 用兩個隊列實作一個棧
queue1出隊一個資料,将這個資料入隊進queue2,直至queue1.size()==1出隊結束。

3.取棧頂(top)

C++ 用兩個隊列實作一個棧
棧頂元素為queue1.head的值。

代碼實作:(代碼中head = back,tail = front)

#include<iostream>
#include<queue>
using namespace std;
//1.用兩個隊列實作一個棧
template<class T>
class Stack
{
private:
	queue<T> queue1;
public:
	void push(T x)
	{
		queue1.push(x);
	}

	void pop()
	{
		queue<T> queue2;//中間局部變量,借用他删除隊頭元素。
		while (queue1.size() > 1)
		{
			queue2.push(queue1.front());
			queue1.pop();
		}
		queue1 = queue2;
	}

	T& top()
	{
		return queue1.back();
	}
};
int main()
{
	Stack<int> st;
	st.push(1);
	st.push(2);
	st.pop();
	st.push(3);
	st.push(4);
	st.pop();
	cout << st.top() << endl;;
    system("pause");
    return 0;
}