码迷,mamicode.com
首页 > 其他好文 > 详细

Min Stack

时间:2015-04-12 13:16:12      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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         if(sta.size() == 0){
 5             sta.push(x);
 6             min.push(x);
 7         }
 8         else{
 9             if(x <= min.top()) min.push(x);
10             sta.push(x);
11         }
12     }
13 
14     void pop() {
15         if(min.top() == sta.top()){
16             sta.pop();
17             min.pop();
18         }
19         else sta.pop();
20     }
21 
22     int top() {
23         return sta.top();
24     }
25 
26     int getMin() {
27         return min.top();
28     }
29 private:
30     stack<int> sta;
31     stack<int> min;
32 };

Min Stack

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4419358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!