@@ -0,0 +1,1862 @@
+package com.pengyifan.leetcode;%0A%0Aimport java.util.Stack;%0A%0A/**%0A * Implement the following operations of a queue using stacks.%0A * %3Cp%3E%0A * %3Cul%3E%0A * %3Cli%3Epush(x) -- Push element x to the back of queue.%3C/li%3E%0A * %3Cli%3Epop() -- Removes the element from in front of queue.%3C/li%3E%0A * %3Cli%3Epeek() -- Get the front element.%3C/li%3E%0A * %3Cli%3Eempty() -- Return whether the queue is empty.%3C/li%3E%0A * %3C/ul%3E%0A * Notes:%0A * %3Cul%3E%0A * %3Cli%3EYou must use only standard operations of a stack -- which means only push to top, peek/pop%0A * from%0A * top, size, and is empty operations are valid.%3C/li%3E%0A * %3Cli%3EDepending on your language, stack may not be supported natively. You may simulate a stack by%0A * using a list or deque (double-ended queue), as long as you use only standard operations of a%0A * stack.%3C/li%3E%0A * %3Cli%3EYou may assume that all operations are valid (for example, no pop or peek operations will be%0A * called on an empty queue).%3C/li%3E%0A * %3C/ul%3E%0A */%0Apublic class ImplementQueueUsingStacks %7B%0A%0A  private Stack%3CInteger%3E stack1 = new Stack%3C%3E();%0A  private Stack%3CInteger%3E stack2 = new Stack%3C%3E();%0A%0A  // Push element x to the back of queue.%0A  public void push(int x) %7B%0A    stack1.push(x);%0A  %7D%0A%0A  // Removes the element from in front of queue.%0A  public void pop() %7B%0A    if (!stack2.isEmpty()) %7B%0A      stack2.pop();%0A    %7D else if (!stack1.isEmpty()) %7B%0A      moveStack1ToStack2();%0A      stack2.pop();%0A    %7D else %7B%0A      ;%0A    %7D%0A  %7D%0A%0A  // Get the front element.%0A  public int peek() %7B%0A    if (!stack2.isEmpty()) %7B%0A      return stack2.peek();%0A    %7D else if (!stack1.isEmpty()) %7B%0A      moveStack1ToStack2();%0A      return stack2.peek();%0A    %7D else %7B%0A      return -1;%0A    %7D%0A  %7D%0A%0A  // Return whether the queue is empty.%0A  public boolean empty() %7B%0A    return stack1.isEmpty() && stack2.isEmpty();%0A  %7D%0A%0A  private void moveStack1ToStack2() %7B%0A    while (!stack1.isEmpty()) %7B%0A      stack2.push(stack1.pop());%0A    %7D%0A  %7D%0A%7D%0A

Implement Queue using Stacks