Create 225. Implement Stack using Queues.md

This commit is contained in:
唐树森 2018-10-16 22:17:21 +08:00 committed by GitHub
parent ec02c248e6
commit beebebcebb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,45 @@
# [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();
}
};
```