描述
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack 类:
MinStack() 初始化堆栈对象。
void push(int val) 将元素val推入堆栈。
void pop() 删除堆栈顶部的元素。
int top() 获取堆栈顶部的元素。
int getMin() 获取堆栈中的最小元素。
分析
数据结构设计题,难在常数时间获取最小值。
使用链表表示栈,结点有表示当前结点及其后面结点最小值的属性,通过这个属性得知这个结点及其后面结点的最小值。
class MinStack {
Node head;
public MinStack() {
head = new Node(0,0);
}
public void push(int val) {
if(head.next == null){
Node node = new Node(val,val);
head.next = node;
}else{
Node node = new Node(val,Math.min(head.next.min,val));
node.next = head.next;
head.next = node;
}
}
public void pop() {
head.next = head.next.next;
}
public int top() {
return head.next.val;
}
public int getMin() {
return head.next.min;
}
}
class Node{
int val;
int min;
Node next;
Node(int val, int min){
this.val = val;
this.min = min;
this.next = null;
}
Node(){}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/