[LeetCode] 232. Implement Queue using Stacks
作者:互联网
mplement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Implement the MyQueue class:
- void push(int x) Pushes element x to the back of the queue.
- int pop() Removes the element from the front of the queue and returns it.
- int peek() Returns the element at the front of the queue.
- boolean empty() Returns true if the queue is empty, false otherwise.
Notes: - You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
Example1:
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
Constraints:
- 1 <= x <= 9
- At most 100 calls will be made to push, pop, peek, and empty.
- All the calls to pop and peek are valid.
这道题也可以采用225题Implement Stack Using Queues那样的方法,但是时间复杂度不是最佳。更好的办法是准备两个栈,一个push栈,一个pop栈。push栈用来接收所有push来的数据,pop栈用来送出pop或者peek的数据。当数据push过来需要被pop的时候,我们可以把之前在push栈里的数据加入到pop栈里,这个时候pop栈最上面的值就是当前最早进入的数据。这个倒数据的过程需要主要亮点,第一是只有在pop栈被pop空了的时候才能倒数据。第二是必须一次性把push栈里现在所有的数据都倒到pop栈里。不遵循这两点数据顺序就会混乱。这个过程中,所有的都是O(1),只有在需要到数据的个别情况时候,是O(N)。
class MyQueue {
Stack<Integer> pushs;
Stack<Integer> pops;
public MyQueue() {
pushs = new Stack<>();
pops = new Stack<>();
}
public void push(int x) {
pushs.add(x);
}
public int pop() {
pushsToPops();
return pops.pop();
}
public int peek() {
pushsToPops();
return pops.peek();
}
public boolean empty() {
return pushs.empty() && pops.empty();
}
private void pushsToPops() {
if (pops.empty()) {
while (!pushs.empty()) {
pops.add(pushs.pop());
}
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
标签:queue,peek,pop,Queue,MyQueue,push,using,Stacks,empty 来源: https://www.cnblogs.com/codingEskimo/p/15812009.html