forked from jvm-coder/Hacktoberfest2022_aakash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse an stack using Recursion.java
More file actions
47 lines (44 loc) · 1.02 KB
/
Reverse an stack using Recursion.java
File metadata and controls
47 lines (44 loc) · 1.02 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
/*
Problem Statement : Reverse an stack using Recursion
TC : O(n^2) SC : O(1) but for Recursive call it uses Auxillary Recursion Stack --> O(2n)
*/
import java.util.*;
public class Main
{
public static void ReverseStack(Stack<Integer> st){
/// B H I
// Base Case
if(st.size()==1){
return;
}
// Hypothesis
int temp = st.pop();
ReverseStack(st);
//Induction
insert(st,temp);
return;
}
public static void insert(Stack<Integer> st , int ele){
/// B H I
//Base
if(st.size()==0){
st.push(ele);
return;
}
/// Hypothesis
int val = st.pop();
insert(st,ele);
//Induction
st.push(val);
return;
}
public static void main(String[] args) {
Stack<Integer> st = new Stack<>();
st.push(2);
st.push(5);
st.push(-3);
st.push(10);
ReverseStack(st);
System.out.println(st);
}
}