LeetCode/225. Implement Stack using Queues.md
2018-10-16 22:17:21 +08:00

46 lines
1.3 KiB
Markdown
Raw 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.

# [225. Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/description/)
# 思路
用队列实现栈。
栈是先进后出队列是后进先出所以要想用队列实现栈时为了返回栈顶元素就得完整pop一遍队列里的元素或者在进队的时候就将栈顶元素移到队头下面的代码采用后者思路。
因为pop和top都要求找到栈顶元素采用前者思路的话会产生混乱。
注意学习stl中queue的一些操作push、pop、front
# 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();
}
};
```