-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStackReverseUsingRecursion.java
More file actions
40 lines (33 loc) · 960 Bytes
/
Copy pathStackReverseUsingRecursion.java
File metadata and controls
40 lines (33 loc) · 960 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
package datastructure.stack.program;
import datastructure.stack.Stack;
public class StackReverseUsingRecursion {
public static void main(String[] args) throws Exception {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
reverse(stack);
System.out.println(stack);
}
// Hold all the elements in the method stack and call insert once the stack
// becomes empty
public static void reverse(Stack<Integer> stack) throws Exception {
if (stack.peek() == null)
return;
int temp = stack.pop();
reverse(stack);
insert(temp, stack);
}
// Hold all the elements in the method stack and push all the data once
// stack becomes empty
private static void insert(int i, Stack<Integer> stack) throws Exception {
if (stack.peek() == null) {
stack.push(i);
} else {
int temp = stack.pop();
insert(i, stack);
stack.push(temp);
}
}
}