[LeetCode155] Min Stack

来源:互联网 发布:jquery copy数据 编辑:程序博客网 时间:2024/05/17 06:09

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.

CC150 原题
class MinStack {    Node top = null;    public void push(int x) {        if(top == null) {            top = new Node(x);            top.min = x;        } else {            Node temp = new Node(x);            temp.next = top;            temp.min = Math.min(x, top.min);            top = temp;        }    }    public void pop() {        top = top.next;        return;    }    public int top() {        if(top != null)            return top.val;        else            return 0;    }    public int getMin() {        if(top != null)            return top.min;        else            return 0;    }        class Node {        int val;        int min;        Node next;        public Node(int val) {            this.val = val;        }    }}


0 0
原创粉丝点击