用链表实现一个栈
重点在结点中设置一个min属性,用来存放当前结点和它下面栈元素的最小值
还有就是利用头插法,简单方便
public class Offer30 {
private Node head;
public Offer30() {
}
public void push(int x) {
//如果当前栈为空 就让头结点指向当前结点,最小值为x
if (head == null) head = new Node(x,x,null);
//如果当前栈不为空 加入到链表中(头插法),并与三个结点的最小值比较,存入较小的那个值
else head = new Node(x,Math.min(head.min,x),head);
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int min() {
return head.min;
}
private class Node{
int val;
int min;
Node next;
public Node(int val,int min,Node next){
this.val = val;
this.min = min;
this.next = next;
}
}