- [x] ##### Min Stack这个题目,用了Node,这个思想很厉害!!!!
- [x] ##### 用Node, 通过一个linked list of nodes, 完成remove 操作,用head一直指向栈顶,
- [x] ##### 并且用一个min永远保存当前最小的min!!!!
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.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); -->Returns -3.
minStack.pop();
minStack.top(); ->Returns 0.
minStack.getMin(); -->Returns -2.//-3已经被pop出去了。怎么更新min value in stack
class MinStack {
/** initialize your data structure here. */
private Node head;
public MinStack() {
}
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;
}
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/