forked from Lonewolf0502/DeveloperCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse a stack using java
More file actions
73 lines (63 loc) · 2.16 KB
/
Reverse a stack using java
File metadata and controls
73 lines (63 loc) · 2.16 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Iterator;
import java.util.Stack;
/**
* Generic methods to reverse stack
* @author Ramesh Fadatare
*
*/
public class StackReversal {
public static <T> void reverseStack(Stack<T> stack) {
if (stack.isEmpty()) {
return;
}
// Remove bottom element from stack
T bottom = popBottom(stack);
// Reverse everything else in stack
reverseStack(stack);
// Add original bottom element to top of stack
stack.push(bottom);
}
private static <T> T popBottom(Stack<T> stack) {
T top = stack.pop();
if (stack.isEmpty()) {
// If we removed the last element, return it
return top;
} else {
// We didn't remove the last element, so remove the last element from what remains
T bottom = popBottom(stack);
// Since the element we removed in this function call isn't the bottom element,
// add it back onto the top of the stack where it came from
stack.push(top);
return bottom;
}
}
private static <T> void printStack(Stack<T> stack){
Iterator<T> iterator = stack.iterator();
while (iterator.hasNext()) {
T t = (T) iterator.next();
System.out.println(t);
}
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
System.out.println("Stack elements before reverse");
printStack(stack);
StackReversal reversal = new StackReversal();
reversal.reverseStack(stack);
System.out.println("Stack after before reverse");
printStack(stack);
Stack<String> stack1 = new Stack<>();
stack1.push("a");
stack1.push("b");
stack1.push("c");
stack1.push("d");
System.out.println("Stack elements before reverse");
printStack(stack1);
reversal.reverseStack(stack1);
System.out.println("Stack after before reverse");
printStack(stack1);
}