forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
42 lines (34 loc) · 1.03 KB
/
ReverseStack.java
File metadata and controls
42 lines (34 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.geeksforgeeks.stack;
import java.util.Stack;
public class ReverseStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("Before Reversing " + stack);
reverseStack(stack);
System.out.println("After Reversing " + stack);
}
public static void reverseStack(Stack<Integer> stack) {
if (!stack.isEmpty()) {
Integer popped = stack.pop();
reverseStack(stack);
insertAtBottom(stack, popped);
}
}
private static void insertAtBottom(Stack<Integer> stack, Integer item) {
if (stack.isEmpty()) {
stack.push(item);
} else {
Integer popped = null;
if (!stack.isEmpty()) {
popped = stack.pop();
insertAtBottom(stack, item);
stack.push(popped);
}
}
}
}