スタックによるキューの実装(C++)


スタックによるキューの実装(C++)
2つのスタックinstackを用意し、outstackがエンキューされたとき、pushがinstackスタックにエンキューされたとき:1.outstackが空の場合、instackスタックの要素の各pushをoutstackにポップアップし、instackからポップアップすると、outstackのスタックトップ要素2がキューからポップアップする.outstackが空でない場合は、outstackスタックの上部要素をポップアップします.
class MyQueue {
     
private:
	void checkoutStack()
	{
     
		if (outstack.empty()) //  
		{
     
			while (!instack.empty())
			{
     
				outstack.push(instack.top());
				instack.pop();
			}
		}
	}
public:

	stack<int> instack;
	stack<int> outstack;

	/** Initialize your data structure here. */
	MyQueue()
	{
     
		
	}

	/** Push element x to the back of queue. */
	void push(int x)
	{
     
		instack.push(x);
	}

	/** Removes the element from in front of queue and returns that element. */
	int pop() {
     
		checkoutStack();

		int tmp = outstack.top();
		outstack.pop();
		return tmp;
	}

	/** Get the front element. */
	int peek()
	{
     
		checkoutStack();
		return outstack.top();
	}

	/** Returns whether the queue is empty. */
	bool empty() {
     
		return instack.empty() && outstack.empty();
	}
};