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.
一道简单的设计题,但是考到了如何实现Stack, 那就是用LinkedList,然后搭建头指针。
和Stack的区别是,这里的node里还保存了一个Min值,类似于Dynamic Programming, 用来取Min值
class Node {
int value;
int min;
Node next;
Node(int x) {
value = x;
next = null;
min = x;
}
}
class MinStack {
Node head;
public void push(int x) {
if (head == null) {
head = new Node(x);
} else {
Node temp = new Node(x);
temp.min = Math.min(head.min, x);
temp.next = head;
head = temp;
}
}
public void pop() {
if (head == null)
return;
head = head.next;
}
public int top() {
if (head == null)
return Integer.MAX_VALUE;
return head.value;
}
public int getMin() {
if (head == null)
return Integer.MAX_VALUE;
return head.min;
}
}