首页 > 代码库 > leetcode 155. Min Stack

leetcode 155. Min Stack

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.
 1 class MinStack { 2 public: 3     void push(int x)  4     { 5         if (minS.empty() || x <= minS.top()) 6             minS.push(x); 7         S.push(x); 8     } 9 10     void pop() 11     {12         if (minS.top() == S.top())13             minS.pop();14         S.pop();15     }16 17     int top() 18     {19         return S.top();    20     }21 22     int getMin() 23     {24         return minS.top();    25     }26     27 private:28     stack<int> S;29     stack<int> minS;30 };

 

leetcode 155. Min Stack