-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin Stack.java
40 lines (32 loc) · 962 Bytes
/
Min 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
/*
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
*/
public class MinStack {
private Point node = new Point(0, Integer.MAX_VALUE, null);
private class Point {
int val, minVal;
Point next;
Point(int val, int minVal, Point next) {
this.val = val;
this.minVal = minVal;
this.next = next;
}
}
public void push(int x) {
Point temp = new Point(x, Math.min(x, (null==node.next ? node.minVal : node.next.minVal)), node.next);
node.next = temp;
}
public void pop() {
node.next = node.next.next;
}
public int top() {
return node.next.val;
}
public int getMin() {
return node.next.minVal;
}
}