-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathminStack.java
More file actions
73 lines (60 loc) · 1.34 KB
/
minStack.java
File metadata and controls
73 lines (60 loc) · 1.34 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
public class MinStack {
Stack<Integer> stack = new Stack<>();
int min = Integer.MAX_VALUE;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(x <= min){
stack.push(min);
min = x;
}
stack.push(x);
}
public void pop() {
if(stack.peek() == min){
stack.pop();
min = stack.pop();
}else{
stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
/*second solution to construct a Node, a variation of LinkedList */
class MinStack {
private Node head;
public void push(int x) {
if(head == null)
head = new Node(x, x);
else
head = new Node(x, Math.min(x, head.min), head);
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
private class Node {
int val;
int min;
Node next;
private Node(int val, int min) {
this(val, min, null);
}
private Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
}