-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathMax Stack.java
85 lines (73 loc) · 1.67 KB
/
Max Stack.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class MaxStack {
private TreeMap<Integer, Stack<Node>> map;
private Node head;
private Node tail;
public MaxStack() {
this.map = new TreeMap<>();
this.head = new Node(-1);
this.tail = new Node(-1);
this.head.next = this.tail;
this.tail.prev = this.head;
}
public void push(int x) {
Node node = createNode(x);
map.computeIfAbsent(x, k -> new Stack<>()).push(node);
}
private Node createNode(int x) {
Node node = new Node(x);
Node prevToTail = tail.prev;
node.next = tail;
tail.prev = node;
prevToTail.next = node;
node.prev = prevToTail;
return node;
}
public int pop() {
Node toRemove = tail.prev;
int val = toRemove.val;
map.get(val).pop();
if (map.get(val).isEmpty()) {
map.remove(val);
}
removeNode(toRemove);
return toRemove.val;
}
public int top() {
return tail.prev.val;
}
public int peekMax() {
return map.lastKey();
}
public int popMax() {
int val = map.lastKey();
Node node = map.get(val).pop();
if (map.get(val).isEmpty()) {
map.remove(val);
}
removeNode(node);
return val;
}
private void removeNode(Node node) {
Node prevNode = node.prev;
Node nextNode = node.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
}
private static class Node {
Node next;
Node prev;
int val;
public Node(int val) {
this.val = val;
}
}
}
/**
* Your MaxStack object will be instantiated and called as such:
* MaxStack obj = new MaxStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.peekMax();
* int param_5 = obj.popMax();
*/