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

Implement Stack using Queues