Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active May 27, 2017 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/f3c50c43cc68072e8c53e106c9f00217 to your computer and use it in GitHub Desktop.
Save anil477/f3c50c43cc68072e8c53e106c9f00217 to your computer and use it in GitHub Desktop.
Reverse a Stack using recursion
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(30);
stack.push(-5);
stack.push(18);
stack.push(14);
stack.push(-3);
stack.push(1);
stack.push(-13);
System.out.println(stack.toString());
sortRecursive(stack);
System.out.println(stack.toString());
}
public static void sortRecursive(Stack<Integer> stack){
if(!stack.isEmpty()){
int temp = stack.pop();
sortRecursive(stack);
insertMinBottom(stack,temp);
}
}
public static void insertMinBottom(Stack<Integer> stack, int temp){
if(stack.isEmpty())
{
stack.push(temp);
}
else
{
int temp2 = stack.pop();
insertMinBottom(stack,temp);
stack.push(temp2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment