Min Stack

来源:互联网 发布:黑米软件怎么样 编辑:程序博客网 时间:2024/05/23 19:27

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

solution:

struct Node {
     int val;
     int min;
     Node *next;
     Node(int x) : val(x), next(NULL) {}
};
class MinStack {
    Node *ntop = NULL;
    public:
        void push(int x) {
            if(ntop==NULL)
            {
                ntop = new Node(x);
                ntop->min = x;
            }
            else
            {
                Node *temp = new Node(x);
                temp->next = ntop;
                ntop = temp;
                ntop->min = ntop->next->min>x?x:ntop->next->min;
            }
        }
     
        void pop() {
            if(ntop==NULL)return;
            ntop = ntop->next;
        }
     
        int top() {
            if(ntop==NULL)return 0;
            return ntop->val;
        }
     
        int getMin() {
            if(ntop==NULL)return 0;
            return ntop->min;
        }
};

0 0
原创粉丝点击