leetcode 225 & 232.Implement Stack using Queues & Implement Queue using Stacks
2017-09-09 11:27
411 查看
突然听人说起有同学做了某游戏公司的笔试题,遇到如何用栈实现队列,想起来自己在半年前做过用队列实现栈和用栈实现队列,现在回忆起来,只记得如果用栈实现队列,忘了用队列实现栈了,在此记录一下。
总所周知,栈是先进先出,队列是先进后出。
对于一个序列来说,一个序列进入队列之后,再出来,序列顺序不变。
在进入栈之后,再出来,序列顺序相反了。
无论是用栈实现队列,还是用队列实现栈,实际上考虑的都是如何将这个序列弄反。
从此思路出发,对于一个队列来说,如果将序列弄反,当然是在每次插入数字的时候,都把整个队列放在新插入数字的后面,这一点用队列是很方便实现的。当然,这样每次push操作的复杂度都在O(n),是很浪费时间的,这个思路的循环相当于又利用一个队列的资源
下面是代码:
至于如何用栈实现队列,可以用两个栈来实现两次序列反转,在这边就不贴代码了,难度也不大。
4000
总所周知,栈是先进先出,队列是先进后出。
对于一个序列来说,一个序列进入队列之后,再出来,序列顺序不变。
在进入栈之后,再出来,序列顺序相反了。
无论是用栈实现队列,还是用队列实现栈,实际上考虑的都是如何将这个序列弄反。
从此思路出发,对于一个队列来说,如果将序列弄反,当然是在每次插入数字的时候,都把整个队列放在新插入数字的后面,这一点用队列是很方便实现的。当然,这样每次push操作的复杂度都在O(n),是很浪费时间的,这个思路的循环相当于又利用一个队列的资源
下面是代码:
class MyStack { public: /** Initialize your data structure here. */ queue<int> que; MyStack() { } /** Push element x onto stack. */ void push(int x) { que.push(x); for(int i=1;i<que.size();++i) { que.push(que.front()); que.pop(); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int result=que.front(); que.pop(); return result; } /** Get the top element. */ int top() { return que.front(); } /** Returns whether the stack is empty. */ bool empty() { return que.empty(); } }; /** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * bool param_4 = obj.empty(); */
至于如何用栈实现队列,可以用两个栈来实现两次序列反转,在这边就不贴代码了,难度也不大。
4000
相关文章推荐
- 【LeetCode】232 & 225 - Implement Queue using Stacks & Implement Stack using Queues
- Implement Stack using Queues && Implement Queue using Stacks (LeetCode)
- leetcode 225|232. Implement Stack using Queues 232. Implement Queue using Stacks
- <LeetCode OJ>Implement Stack using Queues【225】
- Implement Queue by Two Stacks & Implement Stack using Queues
- Implement Stack using Queues && Implement Queue using Stacks
- Leetcode 225 Implement Stack using Queues
- 【LEETCODE】225-Implement Stack using Queues
- Implement Stack using Queues - LeetCode 225
- 【LeetCode-225】 Implement Stack using Queues(C++)
- LeetCode Algorithms #232 <Implement Queue using Stacks>
- 第五题:LeetCode-225-Implement Stack using Queues
- LeetCode 225 Implement Stack using Queues
- Leetcode 225 Implement Stack using Queues
- leetcode 225 Implement Stack using Queues C++
- LeetCode 225 Implement Stack using Queues
- [leetcode-225]Implement Stack using Queues(c++)
- Leetcode 225:Implement Stack using Queues
- LeetCode 225 Implement Stack using Queues(用队列来实现栈)(*)
- 【LeetCode 225_数据结构_栈_实现】Implement Stack using Queues