一、题目描述
二、解题思路
两个栈来回倒腾即可,有两种倒腾方法
- 方法一
push
的时候把主栈内元素全部转移到辅助栈,然后push
进元素,再把辅助栈元素pop
空,并push
回主栈,这样可保证主栈内元素自顶向下符合队列顺序pop
的时候直接pop
- 方法二
push
的时候直接push
,不做调整操作pop
的时候把主栈元素转移到辅助栈,pop
掉辅助栈栈顶元素,再把辅助栈元素转移回主栈
三、解题代码
只用了方法一。方法二大同小异
class MyQueue {
private:
stack<int> s1, s2;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
s1.push(x);
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
auto sln = s1.top();
s1.pop();
return sln;
}
/** Get the front element. */
int peek() {
return s1.top();
}
/** Returns whether the queu e is empty. */
bool empty() {
return s1.size() == 0;
}
};