-
Notifications
You must be signed in to change notification settings - Fork 0
/
a_126_reverse.java
57 lines (45 loc) · 1.4 KB
/
a_126_reverse.java
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
import java.util.Stack;
public class a_126_reverse {
public static String reverseString(String str ){
Stack<Character> s = new Stack<>() ;
int idx = 0 ;
while(idx < str.length() ) {
s.push(str.charAt(idx)) ;
idx++ ;
}
StringBuilder result = new StringBuilder("") ;
while(! s.isEmpty() ){
char curr = s.pop() ;
result.append(curr) ;
}
return result.toString() ;
}
public static void pushAtBottom(Stack<Integer> s , int data){
if( s.isEmpty() ){ // base case
s.push(data) ;
return ;
}
int top = s.pop() ;
pushAtBottom(s, data); // recursion method
s.push(top) ; // backtracks method
}
public static void reverseStack (Stack<Integer> s ){
if(s.isEmpty()){
return ;
}
int top = s.pop() ;
reverseStack(s); // recursion call methode
pushAtBottom(s, top); // back steps ;
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<>() ;
s.push(1) ;
s.push(2) ;
s.push(3) ;
s.push(4) ;
s.push(5) ;
System.out.println(s);
reverseStack(s);
System.out.println(s);
}
}