Leetcode-用队列实现栈

49.题目内容:

Leetcode-用队列实现栈_第1张图片

代码及思路:

class MyStack {
public:
	/** Initialize your data structure here. */
	//因为队列是先进先出的特点,而栈是先进后出的特点,因此使用两个队列搭配使用会更加好理解
	MyStack() {

	}

	/** Push element x onto stack. */
	//入栈
	void push(int x) {
		if (q1.empty())
		{
			q1.push(x);
			while (!q2.empty())  //若此时s2不为空,则将s2的头部元素压入s1,如此类推
			{
				q1.push(q2.front());
				q2.pop();
			}
		}
		else  //s1不为空,s2为空
		{
			q2.push(x);
			while (!q1.empty())
			{
				q2.push(q1.front());
				q1.pop();
			}
		}

	}

	/** Removes the element on top of the stack and returns that element. */
	//两种情况
	int pop() {
		if (!q1.empty())
		{
			int a = q1.front();
			q1.pop();
			return a;
		}
		else if (!q2.empty())
		{
			int a = q2.front();
			q2.pop();
			return a;
		}
		else
			return -1;

	}

	/** Get the top element. */
	int top() {
		if (q1.empty())
		{
			return q2.front();
		}
		else
		{
			return q1.front();
		}
	}

	/** Returns whether the stack is empty. */
	bool empty() {
		return q1.empty() && q2.empty();

	}
private:
	queue q1;
	queue q2;

};
/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

 

你可能感兴趣的:(Leetcode编程题)