Java学习-1
今天学了点Java构建最小栈的方法,采用的是链表存储其中的最小值以及当前节点的数值,在插入栈内新元素的时候进行对应的最小值比对,插入到private链表中。
class ListNode{
public int val;
public int min;
public ListNode next;
public ListNode(int val,int min,ListNode next){
this.val=val;
this.min=min;
this.next=next;
}
}
class MinStack {
private ListNode head;
public MinStack() {
}
private boolean empty(){
return head==null;
}
public void push(int x) {
if(empty()){
head=new ListNode(x,x,null);
}
else{
head=new ListNode(x,Math.min(head.min,x),head);
}
}
public void pop() {
if(empty()){
throw new IllegalStateException("stack is empty!");
}
head=head.next;
}
public int top() {
if(empty()){
throw new IllegalStateException("stack is empty!");
}
return head.val;
}
public int getMin() {
if(empty()){
throw new IllegalStateException("stack is empty!");
}
return head.min;
}
}