包含min函数的栈

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

在栈中包含另一个记录在各元素压入堆栈之后的最小元素下标的数组就可以实现。

  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 //栈功能实现类
  6 template<class T, int capacity>
  7 class min_stack
  8 {
  9 private:
 10     T m_data[capacity];
 11     int m_index[capacity];//保存栈中该元素之前压入栈中的最小元素
 12     int m_pos;
 13 public:
 14     min_stack();
 15     void push(T data);
 16     T pop();
 17     T mim();
 18 };
 19 
 20 /*************************************************
 21 Function:       // min_stack
 22 Description:    // 构造函数
 23 Input:          // 无
 24 Return:         // 无
 25 *************************************************/
 26 template<class T, int capacity>
 27 min_stack<T, capacity>::min_stack()
 28 {
 29     m_pos = -1;
 30 }
 31 
 32 /*************************************************
 33 Function:       // push
 34 Description:    // 入栈函数
 35 Input:          // data: 压入堆栈数据
 36 Return:         // 无
 37 *************************************************/
 38 template<class T, int capacity>
 39 void min_stack<T, capacity>::push(T data)
 40 {
 41     if (m_pos < capacity - 1)
 42     {
 43         m_data[++m_pos] = data;
 44         if(m_pos != 0)
 45         {
 46             if (data < m_data[m_index[m_pos - 1]])
 47             {
 48                 m_index[m_pos] = m_pos;
 49             }
 50             else
 51             {
 52                 m_index[m_pos] = m_index[m_pos - 1];
 53             }
 54         }
 55         else
 56         {
 57             m_index[m_pos] = 0;
 58         }
 59     }
 60     else
 61     {
 62         cout << "over flow" << endl;
 63     }
 64 }
 65 
 66 /*************************************************
 67 Function:       // pop
 68 Description:    // 出栈函数
 69 Input:          // 无
 70 Return:         // T: 返回弹出数据
 71 *************************************************/
 72 template<class T, int capacity>
 73 T min_stack<T, capacity>::pop()
 74 {
 75     if(m_pos < 0)
 76     {
 77         cout << "down flow" << endl;
 78     }
 79     else
 80     {
 81         return m_data[m_pos--];
 82     }
 83 }
 84 
 85 /*************************************************
 86 Function:       // mim
 87 Description:    // 获取栈中最小值
 88 Input:          // 无
 89 Return:         // T: 返回最小数据
 90 *************************************************/
 91 template<class T, int capacity>
 92 T min_stack<T, capacity>::mim()
 93 {
 94     if(m_pos >= 0)
 95     {
 96         return m_data[m_index[m_pos]];
 97     }
 98 }
 99 
100 void main()
101 {
102     min_stack<int, 10>stack;
103     stack.push(5);
104     stack.push(2);
105     stack.push(4);
106     stack.push(2);
107     stack.push(1);
108     for(int i = 0; i < 5; i++)
109     {
110         cout << stack.mim() << endl;
111         stack.pop();
112     }    
113 }

 

posted on 2013-04-09 15:58  blue firmament  阅读(140)  评论(0编辑  收藏  举报