2018-10-16 14:17:21 +00:00
|
|
|
|
# [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++
|
2018-10-16 14:17:21 +00:00
|
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
```
|