[LeetCode]第二十六题 :最小栈

题目描述:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

题目解释:

设计一个栈包含push、pop、top和返回最小值这几个操作。

题目解法:

1.我的解法。设计一个结构,然后实现栈的功能。代码如下:

class MinStack {

    /** initialize your data structure here. */

    private Node head;
    public MinStack() {
        head = new Node(-1);
    }
    
    public void push(int x) {
        Node node = new Node(x);
        node.next = head.next;
        head.next = node;
    }
    
    public void pop() {
        if(head.next != null) {
            Node node = head.next;
            head.next = node.next;
        }
    }
    
    public int top() {
        return head.next.val;
    }
    
    public int getMin() {
        Node work = head.next;
        int min = work.val;
        while(work != null) {
            if(work.val < min) min = work.val;
            work = work.next;
        }
        return min;
    }
    
    class Node {
        int val;
        Node next;
        
        public Node(int x) {
            this.val = x;
        }
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
2.讨论区的解法,牺牲了一部分的空间换取时间。
class MinStack {
    private Node head;
    
    public void push(int x) {
        if(head == null) 
            head = new Node(x, x);
        else 
            head = new Node(x, Math.min(x, head.min), head);
    }

    public void pop() {
        head = head.next;
    }

    public int top() {
        return head.val;
    }

    public int getMin() {
        return head.min;
    }
    
    private class Node {
        int val;
        int min;
        Node next;
        
        private Node(int val, int min) {
            this(val, min, null);
        }
        
        private Node(int val, int min, Node next) {
            this.val = val;
            this.min = min;
            this.next = next;
        }
    }
}

发布了61 篇原创文章 · 获赞 2 · 访问量 8736

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80990788
今日推荐