Last active
May 27, 2017 09:11
-
-
Save anil477/f3c50c43cc68072e8c53e106c9f00217 to your computer and use it in GitHub Desktop.
Reverse a Stack using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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