-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxStackImpl.java
More file actions
122 lines (104 loc) · 3.19 KB
/
MaxStackImpl.java
File metadata and controls
122 lines (104 loc) · 3.19 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import java.util.PriorityQueue;
import java.util.Stack;
public class MaxStackImpl<T extends Comparable<T>> implements MaxStack<T> {
static class LinkedListNode<T> {
T val;
LinkedListNode<T> left;
LinkedListNode<T> right;
public LinkedListNode(T val) {
this.val = val;
left = null;
right = null;
}
}
static class LinkedList<T> {
LinkedListNode<T> head;
LinkedListNode<T> tail;
public LinkedList() {
head = tail = null;
}
public LinkedListNode<T> push(T val) {
LinkedListNode<T> newnode = new LinkedListNode<T>(val);
if (head == null) {
head = tail = newnode;
} else {
// specialized case of a sigle entry
tail.right = newnode;
newnode.left = tail;
tail = newnode;
}
return newnode;
}
public LinkedListNode<T> pop() {
// Remove from tail
LinkedListNode<T> node = tail;
if (tail == null)
return null;
tail = tail.left;
if (tail == null)
head = null;
else {
tail.right = null;
}
return node;
}
public LinkedListNode<T> peek() {
LinkedListNode<T> node = tail;
return node;
}
public void delete(LinkedListNode<T> node) {
if (head == node) {
head = head.right;
if (head != null)
head.left = null;
} else if (tail == node) {
tail = tail.left;
tail.right = null;
} else {
node.right.left = node.left;
node.left.right = node.right;
node.left = node.right = null;
}
}
}
LinkedList<T> list;
PriorityQueue<LinkedListNode<T>> maxHeap;
public MaxStackImpl() {
list = new LinkedList<>();
maxHeap = new PriorityQueue<LinkedListNode<T>>((o1, o2) -> (o2.val - o1.val));
}
/** Add an element to the stack. */
public void push(T toPush) {
LinkedListNode<T> node = list.push(toPush);
maxHeap.add(node);
}
/** Return the top value on the stack. */
public T peek() {
LinkedListNode<T> node = list.peek();
return node.val;
}
/** Remove and return the top value from the stack. */
public T pop() {
LinkedListNode<T> node = list.pop();
if (node != null) {
maxHeap.remove(node);
return node.val;
}
return null;
}
// Two special methods, so this isn't just 'implement a stack':
/** Return the largest value in the stack. (Remember that T must implement Comparable.) */
public T peekMax() {
LinkedListNode<T> node = maxHeap.peek();
return node.val;
}
/** Remove and return the largest value from the stack. */
public T popMax() {
LinkedListNode<T> node = maxHeap.poll();
if (node != null) {
list.delete(node);
return node.val;
}
return null;
}
}