@@ -0,0 +1,1464 @@
+package com.sunny.grokkingalgorithms.misc;%0A%0Aimport java.util.Stack;%0A%0A/**%0A * Created by sundas on 5/10/2017.%0A */%0Apublic class ReverseAStackConstantTime %7B%0A%0A  // Given  s stack reverse it in o(1)%0A%0A  public static Stack%3CInteger%3E reverse(Stack%3CInteger%3E input)%7B%0A    if(input.isEmpty())%7B%0A      return input;%0A    %7D%0A    // empty the list%0A    int cur = input.pop();%0A    reverse(input);%0A    // insert each element at bottom of current stack%0A    insertAtBottom(input,cur);%0A    return input;%0A  %7D%0A%0A  public static void insertAtBottom(Stack%3CInteger%3E input,int curValue)%7B%0A    if(input.isEmpty())%7B%0A      input.push(curValue);%0A    %7D%0A    else%7B%0A      int val = input.pop();%0A      insertAtBottom(input, curValue);%0A      input.push(val);%0A    %7D%0A  %7D%0A%0A  /**%0A   *%0A   * @param args%0A   */%0A  public static void main(String%5B%5D args) %7B%0A    Stack%3CInteger%3E input = new Stack%3C%3E();%0A    input.push(1);%0A    input.push(2);%0A    input.push(3);%0A    input.push(4);%0A    System.out.println(input);%0A    Stack%3CInteger%3E output = reverse(input);%0A    System.out.println(output);%0A    while(!output.isEmpty())%7B%0A      System.out.println(output.pop());%0A    %7D%0A    System.out.println(output);%0A    input.push(8);%0A    input.push(7);%0A    input.push(6);%0A    input.push(5);%0A    input.push(4);%0A    input.push(3);%0A    input.push(2);%0A    input.push(1);%0A    System.out.println(input);%0A    output = reverse(input);%0A    System.out.println(output);%0A    while(!output.isEmpty())%7B%0A      System.out.println(output.pop());%0A    %7D%0A  %7D%0A%0A%7D%0A

Reverse a stack in o(1)