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
package linkedList; | |
import java.util.Stack; | |
public class StackReversal { | |
public static void main(String args[]) { | |
Stack<Integer> stack = new Stack<Integer>(); | |
stack.push(1); | |
stack.push(2); | |
stack.push(3); | |
System.out.println(stack.toString()); | |
reverseStack(stack); | |
System.out.println(stack.toString()); | |
} | |
private static void reverseStack(Stack<Integer> stack) { | |
if(stack.isEmpty()) { | |
return; | |
} | |
int temp =stack.pop(); | |
reverseStack(stack); | |
insertAtBottom(stack,temp); | |
} | |
private static void insertAtBottom(Stack<Integer> stack, int data) { | |
if(stack.isEmpty()) { | |
stack.push(data); | |
return; | |
} | |
int temp = stack.pop(); | |
insertAtBottom(stack, data); | |
stack.push(temp); | |
} | |
} |