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

Min Stack

时间:2015-06-22 09:52:32      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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.

Code:

 1 class MinStack {
 2 public:
 3     void push(int x) {
 4         m_stack.push(x);
 5         if (min_num.empty() || x<min_num.top())
 6            min_num.push(x);
 7         else
 8            min_num.push(min_num.top());
 9     }
10 
11     void pop() {
12         assert( !m_stack.empty() && !min_num.empty() );
13         m_stack.pop();
14         min_num.pop();
15     }
16 
17     int top() {
18             assert( !m_stack.empty() );
19             return m_stack.top();
20     }
21 
22     int getMin() {
23         return min_num.top();
24     }
25 private:
26     stack<int>m_stack;
27     stack<int>min_num;
28 };

 

Min Stack

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4592917.html

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