标签:interview
3.5 Implement a MyQueue class which implements a queue using two stacks.
interface Queue<T> { enqueue(T t); T dequeue(); } class MyQueue<T> implements Queue<T> { MyQueue() { // Init stacks s1 and s2; ... } // O(n) enqueue(T t) { while (!s2.isEmpty()) { s1.push(s2.pop()); } s1.push(t); } // O(n) T dequeue() { while (!s1.isEmpty()) { s2.push(s1.pop()); } return s2.pop(); } private Stack<T> s1; // handle enqueue() private Stack<T> s2; // handle dequeue() } class ABetterQueue<T> implements Queue<T> { ABetterQueue(){...} // O(1) enqueue(T t) { s1.push(t); } // O(n) T dequeue() { if (!s2.isEmpty()) { while(!s1.isEmpty()) s2.push(s1.pop()); } return s2.pop(); } private Stack<T> s1; private Stack<T> s2; }
标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1583036