private class Node {
private int val
;
Node left
;
Node right
;
private Node(int val
) {
this.val
= val
;
}
}
private Node head
= new Node(0);
private Node min
= new Node(0);
public MinStack() {
}
public void push(int x
) {
Node N
= new Node(x
);
head
.right
= N
;
N
.left
= head
;
head
= head
.right
;
Node N_min
= new Node(x
);
if(min
.right
== null
) {
min
.right
= N_min
;
N_min
.left
= min
;
return;
}
Node point
= min
;
while(N_min
.val
> point
.right
.val
) {
point
= point
.right
;
if(point
.right
== null
) {
break;
}
}
if(point
.right
== null
) {
point
.right
= N_min
;
N_min
.left
= point
;
}else {
N_min
.left
= point
;
N_min
.right
= point
.right
;
point
.right
= N_min
;
N_min
.right
.left
= N_min
;
}
}
public void pop() {
Node N
= head
;
head
= head
.left
;
head
.right
= null
;
Node point
= min
.right
;
while(N
.val
!= point
.val
) {
point
= point
.right
;
}
if(point
.right
== null
) {
point
.left
.right
= null
;
point
.left
= null
;
}else {
point
.left
.right
= point
.right
;
point
.right
.left
= point
.left
;
point
.left
= null
;
point
.right
= null
;
}
}
public int top() {
return head
.val
;
}
public int getMin() {
return this.min
.right
.val
;
}
转载请注明原文地址:https://tech.qufami.com/read-19099.html