LeetCode/solutions/232. Implement Queue using Stacks.md

49 lines
1.3 KiB
Markdown
Raw Normal View History

# [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即可。
# C++
2019-09-13 15:08:41 +00:00
``` C++
class MyQueue {
private:
2020-01-30 10:17:25 +00:00
stack<int>stk1; // input
stack<int>stk2; // output
public:
/** Initialize your data structure here. */
2020-01-30 10:17:25 +00:00
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x) {
stk1.push(x);
}
2020-01-30 10:17: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();
stk2.pop();
2020-01-30 10:17:25 +00:00
return res;
}
/** 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();
}
};
```