LeetCode/solutions/232. Implement Queue using Stacks.md
2020-01-30 18:17:25 +08:00

49 lines
1.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [232. Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/description/)
# 思路
用两个栈实现队列。
设置两个栈stk1和stk2基本思路是stk1用作input入队, stk2用作output出队
入队无脑入栈stk1即可
出队若stk2为空那么先将stk1所有元素依次pop然后push进stk2此时stk2栈顶元素就是最开始入队的元素所以pop即可。
# C++
``` C++
class MyQueue {
private:
stack<int>stk1; // input
stack<int>stk2; // output
public:
/** Initialize your data structure here. */
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x) {
stk1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res = peek();
stk2.pop();
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();
}
};
```