forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseStack.java
54 lines (41 loc) · 1.06 KB
/
ReverseStack.java
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
43
44
45
46
47
48
49
50
51
52
53
54
package stacks;
import java.util.Stack;
public class ReverseStack {
/*
* Reverse a stack
* */
private static Stack<Character> stack = new Stack<>();
public static void reverseStack() {
if(!stack.isEmpty()) {
char c = stack.peek();
stack.pop();
reverseStack();
insertAtBottom(c);
}
}
private static void insertAtBottom(char c) {
if(stack.isEmpty()) {
stack.push(c);
} else {
char a = stack.peek();
stack.pop();
insertAtBottom(c);
stack.push(a);
}
}
public static void main(String[] args) {
// push elements into
// the stack
stack.push('1');
stack.push('2');
stack.push('3');
stack.push('4');
System.out.println("Original Stack");
System.out.println(stack);
// function to reverse
// the stack
reverseStack();
System.out.println("Reversed Stack");
System.out.println(stack);
}
}