LeetCode 155. 最小栈 双链表

LeetCode 155. 最小栈 双链表

题目

	155. 最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
 

示例:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
 

提示:

pop、top 和 getMin 操作总是在 非空栈 上调用。

思路

用链表模拟,记录一个last指针以便加速,遇到删除最小值的情况,就重新遍历最小值,当然也可以用一个容器优化
到nlongn,懒得写了

代码

class MinStack {
	final node head;
	node last;
	int min = Integer.MAX_VALUE;
	static class node {
		int val;
		node next;
		node pre;
		public node(int val, node next, node pre) {
			this.val = val;
			this.next = next;
            this.pre=pre;
		}
	}

	public MinStack() {
		head = new node(Integer.MIN_VALUE, null, null);
		last = head;
	}

	public void push(int x) {
		last.next = new node(x, null, last);
		last = last.next;
		min = Math.min(x, min);

	}

	public void pop() {
        //确保头节点不会被删除
       if(last ==head )return ;
       //检查删除是否为最小值
       if(last.val==min){
           min=Integer.MAX_VALUE;
           node tmp=head.next;
           while(tmp!=last){
               min=Math.min(tmp.val,min);
               tmp=tmp.next;
           }
       }
     
       //删除尾节点操作
        last=last.pre;
        
        last.next=null;
        
        
        
	}
    public void printList(){
        node tmp=head.next;
        while(tmp!=null){
            System.out.print(tmp.val+" ");
            tmp=tmp.next;
            }
        System.out.println();
    }
	public int top() {
		return last.val;

	}

	public int getMin() {
		return min;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_42499133/article/details/106067122