-
Notifications
You must be signed in to change notification settings - Fork 0
/
sortingStack.java
62 lines (44 loc) · 1.37 KB
/
sortingStack.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
import java.util.Stack;
public class MyClass {
public static void main(String args[]) {
Stack stack = new Stack();
stack.push(9);
stack.push(1);
stack.push(3);
stack.push(6);
stack.push(8);
stack.push(10);
Stack sortedStack = sortStack(stack);
while (!sortedStack.isEmpty())
{
System.out.println(sortedStack.pop());
}
}
public static Stack sortStack(Stack stack){
Stack sortedStack =new Stack();
while(!stack.isEmpty()){
if(sortedStack.isEmpty()){
sortedStack.push(stack.pop());
// System.out.println(sortedStack.peek());
}
else {
// sortedStack.push(stack.pop());
int count = 0;
int temp = (int) stack.pop();
// System.out.println(temp);
while(!sortedStack.isEmpty() && temp <= (int)sortedStack.peek()){
stack.push(sortedStack.pop());
count++;
}
//
sortedStack.push(temp);
//
while(count > 0){
sortedStack.push(stack.pop());
count--;
}
}
}
return sortedStack;
}
}