-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStack.java
More file actions
49 lines (42 loc) · 1.07 KB
/
Copy pathReverseStack.java
File metadata and controls
49 lines (42 loc) · 1.07 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
import java.util.Stack;
public class ReverseStack {
public static void reverseStack(Stack <Integer> s){
Stack <Integer> st = new Stack<>();
while(!s.isEmpty()){
st.push(s.pop());
}
while(!st.isEmpty()){
System.out.println(st.peek());
st.pop();
}
}
public static void pushBottom(Stack <Integer> s, int data){
if(s.isEmpty()){
s.push(data);
return;
}
int top = s.pop();
pushBottom(s, data);
s.push(top);
}
public static void reverseStackoptimised(Stack <Integer> s){
if(s.isEmpty()){
return;
}
int top = s.pop();
reverseStackoptimised(s);
pushBottom(s, top);
}
public static void main(String args[]){
Stack <Integer> s = new Stack<>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
reverseStackoptimised(s);
while(!s.isEmpty()){
System.out.println(s.peek());
s.pop();
}
}
}