包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
 
 1 class Solution {
 2 public:
 3     Solution():MIN(-1){}
 4     std::vector<int> vv;
 5     int MIN;
 6     void push(int value) {
 7         if (MIN == -1)
 8         {
 9             MIN = value;
10         }
11         else
12         {
13             if (value < MIN)
14             {
15                 MIN = value;
16             }
17         }
18         vv.push_back(value);
19     }
20     void pop() {
21         if (vv.empty())
22             return;
23 
24         if (vv[vv.size()-1] <= MIN)
25         {
26             MIN = 999999;
27             int len = vv.size()-1;
28             for (int i = 0 ; i < len ;++i)
29             {
30                 if (MIN > vv[i])
31                     MIN = vv[i];
32             }
33         }
34 
35         vv.pop_back();
36     }
37     int top() {
38         if (vv.empty())
39             return -1;
40         return vv[vv.size()-1];
41     }
42     int min() {
43         return MIN;
44     }
45 };
原文地址:https://www.cnblogs.com/xiaoyesoso/p/5149714.html