2018-10-16 15:12:25 +00:00
|
|
|
|
# [232. Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/description/)
|
|
|
|
|
# 思路
|
2020-01-30 10:17:25 +00:00
|
|
|
|
用两个栈实现队列。
|
|
|
|
|
设置两个栈stk1和stk2,基本思路是stk1用作input(入队), stk2用作output(出队)。
|
|
|
|
|
|
|
|
|
|
入队:无脑入栈stk1即可;
|
|
|
|
|
出队:若stk2为空,那么先将stk1所有元素依次pop然后push进stk2,此时stk2栈顶元素就是最开始入队的元素,所以pop即可。
|
|
|
|
|
|
2018-10-16 15:12:25 +00:00
|
|
|
|
# C++
|
2019-09-13 15:08:41 +00:00
|
|
|
|
``` C++
|
2018-10-16 15:12:25 +00:00
|
|
|
|
class MyQueue {
|
|
|
|
|
private:
|
2020-01-30 10:17:25 +00:00
|
|
|
|
stack<int>stk1; // input
|
|
|
|
|
stack<int>stk2; // output
|
2018-10-16 15:12:25 +00:00
|
|
|
|
public:
|
|
|
|
|
/** Initialize your data structure here. */
|
2020-01-30 10:17:25 +00:00
|
|
|
|
MyQueue() {}
|
|
|
|
|
|
2018-10-16 15:12:25 +00:00
|
|
|
|
/** Push element x to the back of queue. */
|
|
|
|
|
void push(int x) {
|
|
|
|
|
stk1.push(x);
|
|
|
|
|
}
|
2020-01-30 10:17:25 +00:00
|
|
|
|
|
2018-10-16 15:12:25 +00:00
|
|
|
|
/** Removes the element from in front of queue and returns that element. */
|
|
|
|
|
int pop() {
|
2020-01-30 10:17:25 +00:00
|
|
|
|
int res = peek();
|
2018-10-16 15:12:25 +00:00
|
|
|
|
stk2.pop();
|
2020-01-30 10:17:25 +00:00
|
|
|
|
return res;
|
2018-10-16 15:12:25 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Get the front element. */
|
|
|
|
|
int peek() {
|
|
|
|
|
if(stk2.empty()){
|
|
|
|
|
int tmp;
|
|
|
|
|
while(!stk1.empty()){
|
|
|
|
|
tmp = stk1.top();
|
|
|
|
|
stk1.pop();
|
|
|
|
|
stk2.push(tmp);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return stk2.top();
|
|
|
|
|
}
|
|
|
|
|
/** Returns whether the queue is empty. */
|
|
|
|
|
bool empty() {
|
|
|
|
|
return stk1.empty() && stk2.empty();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|