21 The stack containing the min function

To define the data structure of the stack, please implement a min function in this type that can get the smallest element of the stack.

 

 

C++:

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324979493&siteId=291194637