-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack2.java
More file actions
61 lines (51 loc) · 1.03 KB
/
Stack2.java
File metadata and controls
61 lines (51 loc) · 1.03 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
package code.leetcode;
/**
* 题目:用数组实现一个栈,实现pop,push,peak,getMin方法,确保每个方法时间复杂度为O(1)
*
* @author issuser
*
*/
public class Stack2 {
static class Node {
int val;
}
static class NodeWithMin {
Node node;
Node minNode;
public NodeWithMin(Node node, Node minNode) {
this.node = node;
this.minNode = minNode;
}
}
private NodeWithMin[] stack = new NodeWithMin[10];
private int head = -1, tail = 0;
public Node pop() {
if (tail > head)
return null;
NodeWithMin node = stack[head];
stack[head--] = null;
// node.minNode = null;
return node.node;
}
public Node peak() {
if (tail > head)
return null;
return stack[head].node;
}
public void push(Node node) {
if (node == null)
return;
Node minNode = this.getMin();
if (minNode == null)
minNode = node;
stack[++head] = new NodeWithMin(node, minNode);
}
public Node getMin() {
if (tail > head)
return null;
NodeWithMin node = stack[head];
if (node == null)
return null;
return node.minNode;
}
}