标签:initial 最小栈 时间 来源 data min() head private code
class MinStack {
private Stack<Integer> stackmin;
private Stack<Integer> stack;
/** initialize your data structure here. */
public MinStack() {
stackmin = new Stack<>();
stack = new Stack<>();
}
// 将元素 x 推入栈中
public void push(int x) {
if(stack.size() == 0) {
stackmin.push(x);
} else {
int min = stackmin.peek();
stackmin.push(Math.min(min, x));
}
stack.push(x);
}
// 删除栈顶的元素
public void pop() {
stackmin.pop();
stack.pop();
}
// 获取栈顶元素
public int top() {
return stack.peek();
}
// 能在常数时间内检索到最小元素
public int getMin() {
return stackmin.peek();
}
}
class MinStack {
class Node{
int value;
int min;
Node next;
Node(int x, int min){
this.value=x;
this.min=min;
next = null;
}
}
Node head;
//每次加入的节点放到头部
public void push(int x) {
if(null==head){
head = new Node(x,x);
}else{
//当前值和之前头结点的最小值较小的做为当前的 min
Node n = new Node(x, Math.min(x,head.min));
n.next=head;
head=n;
}
}
public void pop() {
if(head!=null)
head =head.next;
}
public int top() {
if(head!=null)
return head.value;
return -1;
}
public int getMin() {
if(null!=head)
return head.min;
return -1;
}
}
作者:windliang
链接:https://leetcode-cn.com/problems/min-stack/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-38/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签:initial 最小栈 时间 来源 data min() head private code
原文地址:https://www.cnblogs.com/angelica-duhurica/p/12237961.html