225. 用队列实现栈
\请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
class MyStack {queue<int> s1;queue<int> s2;
public:MyStack() {}void push(int x) {if(s1.empty() && !s2.empty()){s1.push(x);int tmp;while(!s2.empty()){tmp=s2.front();s1.push(tmp);s2.pop();}}else if(s2.empty() && !s1.empty()){s2.push(x);int tmp;while(!s1.empty()){tmp=s1.front();s2.push(tmp);s1.pop();}}else{s1.push(x);}}int pop() {if(s1.empty() && !s2.empty()){int tmp = s2.front();s2.pop();return tmp;}else{int tmp=s1.front();s1.pop();return tmp;}}int top() {if(s1.empty() && !s2.empty()){return s2.front();}else{return s1.front();}}bool empty() {return s1.empty() && s2.empty();}
};/*** 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();*/