forked from kexun/sort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SortStackByStack.java
58 lines (50 loc) · 1.07 KB
/
SortStackByStack.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
package com.demo;
import java.util.Stack;
/**
* 对栈进行排序,但是只能利用一个辅助栈,已经一个辅助变量。
* @author kexun
*
*/
public class SortStackByStack {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(1);
stack.push(10);
stack.push(3);
stack.push(1);
stack.push(14);
stack.push(0);
stack.push(4);
stack.push(4);
SortStackByStack s = new SortStackByStack();
s.sort(stack);
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
public void sort(Stack<Integer> stack) {
Stack<Integer> help = new Stack<Integer>();
while (!stack.isEmpty()) {
Integer temp = stack.pop();
if (help.isEmpty()) {
help.push(temp);
} else {
if (temp > help.peek()) {
while (!help.isEmpty()) {
Integer helpItem = help.peek();
if (temp > helpItem) {
help.pop();
stack.push(helpItem);
} else {
break;
}
}
}
help.push(temp);
}
}
while (!help.isEmpty()) {
stack.push(help.pop());
}
}
}