剑指offer---包含min函数的栈

题目包含min函数的栈

要求:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

class Solution {
public:
    void push(int value) {
        
    }
    void pop() {
        
    }
    int top() {
        
    }
    int min() {
        
    }
};

 

解题代码:

 1 class Solution {
 2 public:
 3     void push(int value) {
 4         if(stack1.empty())
 5             stack2.push(value);
 6         else
 7             if(value < stack2.top())
 8                 stack2.push(value);
 9             else
10                 stack2.push(stack2.top());
11 
12         stack1.push(value);
13     }
14 
15     void pop() {
16         stack1.pop();
17         stack2.pop();
18     }
19 
20     int top() {
21         return stack1.top();
22     }
23 
24     int min() {
25         return stack2.top();
26     }
27 private:
28     stack<int> stack1;
29     stack<int> stack2;
30 };

 

posted on 2018-10-29 17:12  wangzhch  阅读(137)  评论(0编辑  收藏  举报

导航