LeetCode/solutions/225. Implement Stack using Queues.md

46 lines
1.4 KiB
Markdown
Raw Normal View History

# [225. Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/)
# 思路
用队列实现栈。
栈是先进后出队列是后进先出所以要想用队列实现栈时为了返回栈顶元素就得完整pop一遍队列里的元素或者在进队的时候就将栈顶元素移到队头下面的代码采用后者思路。
因为pop和top都要求找到栈顶元素采用前者思路的话会产生混乱。
注意学习stl中queue的一些操作push、pop、front
# C++
2019-09-13 15:08:41 +00:00
``` C++
class MyStack {
private:
queue<int>q;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) { // 先将x进队然后再将x前面的元素依次pop出来并入队尾这样x就位于队头了。
q.push(x);
int tmp;
for(int i = 0; i < q.size() - 1; i++){
tmp = q.front();
q.pop();
q.push(tmp);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int res = q.front();
q.pop();
return res;
}
/** Get the top element. */
int top() {
return q.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
```