設計包含min函數的棧(源碼)

來源:互聯網
上載者:User

採用兩個雙端隊列實現,一個存資料,一個是輔助棧,存第一個棧的最小元素的地址,實現技巧在於輔助棧存放的是第一個棧的最小元素的地址,難度在於使用模板實現。

#include <deque>
#include <assert.h>
#include <iostream>

using namespace std;

template <typename T>class CStackWithMin
{
public:
 CStackWithMin(void){}
 virtual ~CStackWithMin(void){}

 T& top(void);
 const T&top(void)const;

 void push(const T& value);
 void pop(void);

 const T& min(void) const;

 const T& size(void) const;

private:
 deque<T> m_data;//the element of the stack
 deque<size_t> m_minIndex; //the index of minimum elements
};

template<typename T> T& CStackWithMin<T>::top()
{
 return m_data.back();
}

template<typename T> const T& CStackWithMin<T>::top() const
{
 return m_data.back();
}

template<typename T> void CStackWithMin<T>::push(const T& value)
{
 m_data.push_back(value);

 if (m_minIndex.size()==0)
 {
  m_minIndex.push_back(0);
 }
 else
 {
  if(value<m_data[m_minIndex.back()])
   m_minIndex.push_back(m_data.size()-1);
  else
   m_minIndex.push_back(m_minIndex.back());
 }
}

template<typename T> void CStackWithMin<T>::pop()
{
 m_data.pop_back();

 m_minIndex.pop_back();
}

template<typename T>const T& CStackWithMin<T>::min()const
{
 assert(m_data.size()>0);
 assert(m_minIndex.size()>0);

 return m_data[m_minIndex.back()];
}

template<typename T>const T& CStackWithMin<T>::size() const
{
 assert(m_data.size()>0);
 assert(m_minIndex.size()>0);

 return m_data.size();
}

int main()
{
 CStackWithMin<int> cs;

 cs.push(3);
 cs.push(4);
 cs.push(2);
 cs.push(1);
 cs.push(5);
 cs.push(6);
 cs.push(0);
 cout<<"cs.size() = "<<cs.size()<<endl;
 int len=cs.size();
 for (int i=0; i<len; i++)
 {
  cout<<"cs.min() = "<<cs.min()<<endl;
  cout<<"cs.top() = "<<cs.top()<<endl;
  cs.pop();
 }

 return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.