设计包含min函数的栈

来源:互联网 发布:真小人 伪君子知乎 编辑:程序博客网 时间:2024/06/02 05:06

定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素,要求函数min,push及pop的时间复杂度都是O(1)

栈的数据结构包含两个普通栈,一个栈存数据,另一个栈存最小值(或最小值的位置,如果用stl里的栈,则不能存最小值的位置,因为stl里的stack不支持下标索引访问)。

[cpp] view plaincopyprint?
  1. #include <iostream>   
  2. #include <stack>   
  3. #include <assert.h>   
  4. using namespace std;  
  5.   
  6. template <typename T>  
  7. class StackWithMin  
  8. {  
  9. private:  
  10.     stack<T> datastack;  
  11.     stack<T> minstack;//存最小值而不是最小值的下标  
  12. public:  
  13.     void push(const T &data)  
  14.     {  
  15.         datastack.push(data);  
  16.         if(0==minstack.size())  
  17.             minstack.push(data);  
  18.         else if(minstack.top()>data)  
  19.             minstack.push(data);  
  20.         else  
  21.             minstack.push(minstack.top());  
  22.     }  
  23.     void pop()  
  24.     {  
  25.         assert(datastack.size()>0);  
  26.         assert(minstack.size()>0);  
  27.         datastack.pop();  
  28.         minstack.pop();  
  29.     }  
  30.     int& min()  
  31.     {  
  32.         return minstack.top();  
  33.     }  
  34.   
  35. };  
  36.   
  37. void main()  
  38. {  
  39.     StackWithMin<int> s;  
  40.     s.push(10);  
  41.     s.push(7);  
  42.     s.push(3);  
  43.     s.push(3);  
  44.     s.push(8);  
  45.     s.push(5);  
  46.     s.push(2);  
  47.     s.push(6);  
  48.     for(int i=0; i<8; i++)  
  49.     {  
  50.         cout<<s.min()<<endl;  
  51.         s.pop();  
  52.     }  
  53.   
  54. }  
原创粉丝点击