Implement the following operations of a stack using queues.
Notes:
push to back
, peek/pop from front
, size
, and is empty
operations are valid.
这道题可以用一个queue实现,我却用了两个。。。两个queue的思路就是一个queue里面放顶点,另一个queue里面按照stack顺序存储。
代码写的很长。。。
public class MyStack { Queue<Integer> q1; Queue<Integer> q2; boolean isQ1; /** Initialize your data structure here. */ public MyStack() { q1 = new LinkedList<>(); q2 = new LinkedList<>(); isQ1 = true; } /** Push element x onto stack. */ public void push(int x) { if (q1.isEmpty()) { q1.offer(x); isQ1 = true; } else if (q2.isEmpty()) { q2.offer(x); isQ1 = false; } else if (isQ1) { while (!q2.isEmpty()) { q1.offer(q2.poll()); } q2.offer(x); isQ1 = false; } else { while (!q1.isEmpty()) { q2.offer(q1.poll()); } q1.offer(x); isQ1 = true; } } /** Removes the element on top of the stack and returns that element. */ public int pop() { int x = 0; if (isQ1) { x = q1.poll(); if (!q2.isEmpty()) { q1.offer(q2.poll()); } } else { x = q2.poll(); if (!q1.isEmpty()) { q2.offer(q1.poll()); } } return x; } /** Get the top element. */ public int top() { if (isQ1) { return q1.peek(); } return q2.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { if (q1.size() == 0 && q2.size() == 0) { return true; } return false; } } /** * 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(); * boolean param_4 = obj.empty(); */
一个queue的思路就是每次enqueue, dequeue。
public class MyStack { Queue<Integer> q; /** Initialize your data structure here. */ public MyStack() { q = new LinkedList<>(); } /** Push element x onto stack. */ public void push(int x) { q.offer(x); for (int i = 0; i < q.size() - 1; i++) { q.offer(q.poll()); } } /** Removes the element on top of the stack and returns that element. */ public int pop() { return q.poll(); } /** Get the top element. */ public int top() { return q.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return q.isEmpty(); } } /** * 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(); * boolean param_4 = obj.empty(); */
这个算法果然跑得很快。。。只有push的时候是O(n)。因为push的时候就是按照stack的顺序push进去的。
Implement Stack using Queues Leetcode
原文:http://www.cnblogs.com/aprilyang/p/6385560.html