-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy path栈排序.java
More file actions
71 lines (57 loc) · 1.53 KB
/
Copy path栈排序.java
File metadata and controls
71 lines (57 loc) · 1.53 KB
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
71
package io.github.dunwu.algorithm.stack;
import org.junit.jupiter.api.Assertions;
import java.util.Stack;
/**
* <a href="https://leetcode.cn/problems/sort-of-stacks-lcci/">面试题 03.05. 栈排序</a>
*
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @date 2025-11-26
*/
public class 栈排序 {
public static void main(String[] args) {
SortedStack s = new SortedStack();
s.push(1);
s.push(2);
Assertions.assertEquals(1, s.peek());
s.pop();
Assertions.assertEquals(2, s.peek());
SortedStack s2 = new SortedStack();
s2.pop();
s2.pop();
s2.push(1);
s2.pop();
Assertions.assertTrue(s2.isEmpty());
}
static class SortedStack {
private Stack<Integer> s;
private Stack<Integer> t;
public SortedStack() {
s = new Stack<>();
t = new Stack<>();
}
public void push(int val) {
if (s.isEmpty()) {
s.push(val);
return;
}
while (!s.isEmpty() && s.peek() < val) {
t.push(s.pop());
}
s.push(val);
while (!t.isEmpty()) {
s.push(t.pop());
}
}
public void pop() {
if (!s.isEmpty()) {
s.pop();
}
}
public int peek() {
return s.isEmpty() ? -1 : s.peek();
}
public boolean isEmpty() {
return s.isEmpty();
}
}
}