-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack_03.java
More file actions
44 lines (34 loc) · 966 Bytes
/
Copy pathStack_03.java
File metadata and controls
44 lines (34 loc) · 966 Bytes
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
// Reverse a Stack
import java.util.Stack;
public class Stack_03 {
// Helper function to insert an element at the bottom of the stack
static void insertAtBottom(Stack<Integer> st, int item) {
if (st.isEmpty()) {
st.push(item);
return;
}
int topElem = st.pop();
insertAtBottom(st, item);
st.push(topElem);
}
// Main function to reverse the stack
static void reverseStack(Stack<Integer> st) {
if (st.isEmpty()) {
return;
}
int item = st.pop();
reverseStack(st);
insertAtBottom(st, item);
}
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(stack);
reverseStack(stack);
System.out.println(stack);
}
}