兩個隊列類比一個棧,兩個隊列類比

來源:互聯網
上載者:User

兩個隊列類比一個棧,兩個隊列類比

#include <iostream>  #include <assert.h>  #include <queue>  using namespace std;  /*兩個隊列類比一個堆棧*/  /*隊列A、B 入棧:將元素依次壓入到非空的隊列,第一個元素壓倒對列A 出棧:把隊列A的前n-1個元素倒到隊列B,把第n個元素去掉。此時資料在B中,下次操作,則對B操作。 棧頂:把隊列A的前n-1個元素倒到隊列B,把第n個元素作為棧頂*/  template <typename T>  class MyStack  {  public:      //入棧,第一個元素進到隊列deque1,以後每個元素進到非空的隊列      void  push(const T &element) ;     //出棧,將非空隊列的前n-1個元素轉移到另一個空的隊列,刪除非空隊列的第n個元素      void pop() ;     //棧頂元素,將非空隊列的前n-1個元素轉移到另一個空的隊列,將非空隊列的第n個元素返回      T top();      //棧是否為空白      bool empty()      {          return (q1.empty()&&q2.empty());      }  private:      queue<T> q1;      queue<T> q2;  };  template<typename T> void MyStack<T>::push(const T &element){  if (q1.empty() && q2.empty())  {  q1.push(element);  }  else if (!q1.empty() && q2.empty())  {  q1.push(element);  }  else if (q1.empty() && !q2.empty())  {  q2.push(element);  }  }  template<typename T>void MyStack<T>::pop(){  if (!q1.empty())  {  int size = q1.size();  for (int i=0; i<size-1; i++)  {  q2.push(q1.front());  q1.pop();  }  q1.pop();  }  else  {  int size = q2.size();  for (int i=0; i<size-1; i++)  {  q1.push(q2.front());  q2.pop();  }  q2.pop();  }  } template <typename T>T MyStack<T>::top(){  if (!q1.empty())  {  int size = q1.size();  for (int i=0; i<size-1; i++)  {  q2.push(q1.front());  q1.pop();  }  T temp = q1.front();  q1.pop();  q2.push(temp);  return temp;  }  else  {  int size = q2.size();  for (int i=0; i<size-1; i++)  {  q1.push(q2.front());  q2.pop();  }  T temp = q2.front();  q2.pop();  q1.push(temp);  return temp;  }  }   int main(int argc, char *argv[])  {      MyStack<int> my;      for (int i=0; i<10; i++)      {          my.push(i);      }      while (!my.empty())      {          cout<<my.top()<<" ";          my.pop();      }      cout<<endl;  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.