-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortAnotherStack.java
70 lines (56 loc) · 1.61 KB
/
SortAnotherStack.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
60
61
62
63
64
65
66
67
68
69
70
package Stack;
import java.util.ListIterator;
public class SortAnotherStack {
static void sortedInsert(Stack<Integer> s, int x)
{
// Base case: Either stack is empty or newly
// inserted item is greater than top (more than all
// existing)
if (s.isEmpty() || x > s.peek()) {
s.push(x);
return;
}
// If top is greater, remove the top item and recur
int temp = s.pop();
sortedInsert(s, x);
// Put back the top item removed earlier
s.push(temp);
}
static void sortStack(Stack<Integer> s)
{
// If stack is not empty
if (!s.isEmpty()) {
// Remove the top item
int x = s.pop();
// Sort remaining stack
sortStack(s);
// Push the top item back in sorted stack
sortedInsert(s, x);
}
}
static void printStack(Stack<Integer> s)
{
ListIterator<Integer> lt = s.listIterator();
// forwarding
while (lt.hasNext())
lt.next();
// printing from top to bottom
while (lt.hasPrevious())
System.out.print(lt.previous() + " ");
}
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
s.push(30);
s.push(-5);
s.push(18);
s.push(14);
s.push(-3);
System.out.println(
"Stack elements before sorting: ");
printStack(s);
sortStack(s);
System.out.println(
" \n\nStack elements after sorting:");
printStack(s);
}
}