-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathSort_a_stack.java
59 lines (51 loc) · 1.16 KB
/
Sort_a_stack.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
58
59
// { Driver Code Starts
import java.util.Scanner;
import java.util.Stack;
class SortedStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
Stack<Integer> s = new Stack<>();
int n = sc.nextInt();
while (n-- > 0)
s.push(sc.nextInt());
GfG g = new GfG();
Stack<Integer> a = g.sort(s);
while (!a.empty()) {
System.out.print(a.peek() + " ");
a.pop();
}
System.out.println();
}
}
}
class GfG {
public Stack<Integer> sort(Stack<Integer> s) {
if (s == null || s.isEmpty()) {
return s;
} else {
int x = s.pop();
sort(s);
insertAtBottom(s, x);
}
// Stack<Integer> st = new Stack<Integer>();
// while( !s.isEmpty() ){
// int top = s.pop();
// while( !st.isEmpty() && top < st.peek() ){
// s.push(st.pop());
// }
// st.push(top);
// }
return s;
}
public void insertAtBottom(Stack<Integer> s, int x) {
if (s.isEmpty() || x > s.peek()) {
s.push(x);
} else {
int a = s.pop();
insertAtBottom(s, x);
s.push(a);
}
}
}