-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyStack.java
52 lines (46 loc) · 1.17 KB
/
MyStack.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
public class MyStack<T extends Comparable<T>> {
private class Node {
T data;
Node next = null;
T min = null;
public Node(T data) {
this.data = data;
}
}
private Node top;
private T globalMin = null;
public void push(T data) {
Node newNode = new Node(data);
newNode.next = top;
top = newNode;
if(globalMin == null) {
globalMin = data;
} else if (globalMin.compareTo(data) > 0) {
globalMin = data;
}
newNode.min = globalMin;
}
public T pop() {
if (top == null) { throw new RuntimeException("stack underflow"); }
T returnVal = this.top.data;
top = top.next;
if (top == null) {
globalMin = null;
} else {
globalMin = top.min;
}
return returnVal;
}
public T min() {
return globalMin;
}
public String toString() {
StringBuffer sb = new StringBuffer();
Node cur = top;
while (cur != null) {
sb.append(cur.data + "\n");
cur = cur.next;
}
return sb.toString();
}
}