Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. 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, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
Lintcode: http://www.cnblogs.com/EdwardLiu/p/4278333.html
1 class MyQueue { 2 // Push element x to the back of queue. 3 LinkedList<Integer> stack1; 4 LinkedList<Integer> stack2; 5 6 public MyQueue() { 7 this.stack1 = new LinkedList<Integer>(); 8 this.stack2 = new LinkedList<Integer>(); 9 } 10 11 public void push(int x) { 12 stack1.push(x); 13 } 14 15 // Removes the element from in front of queue. 16 public void pop() { 17 if (!stack2.isEmpty()) { 18 stack2.pop(); 19 return; 20 } 21 while (!stack1.isEmpty()) { 22 stack2.push(stack1.pop()); 23 } 24 if (!stack2.isEmpty()) stack2.pop(); 25 } 26 27 // Get the front element. 28 public int peek() { 29 if (!stack2.isEmpty()) return stack2.peek(); 30 else while (!stack1.isEmpty()) { 31 stack2.push(stack1.pop()); 32 } 33 return stack2.peek(); 34 } 35 36 // Return whether the queue is empty. 37 public boolean empty() { 38 return (stack1.isEmpty() && stack2.isEmpty()); 39 } 40 }