雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

數(shù)據(jù)結構用兩個棧實現(xiàn)一個隊列的實例

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

數(shù)據(jù)結構用兩個棧實現(xiàn)一個隊列的實例

棧是先進后出,隊列是先進先出

每次元素都push在st1中,pop的時候如果st2為空,將st1的棧頂元素放在st2的棧底,這樣st1的所有元素都放在st2中,st1的棧底就是st2的棧頂,pop st2的棧頂,這樣就滿足了隊列的先進先出。

#include <iostream>
using namespace std;
#include <stack>
#include <stdlib.h>

template <class T>
class SQueue {
public:
  void Push(const T& value);
  T Pop();
private:
  stack<T> st1;
  stack<T> st2;
};

template <class T>
T SQueue<T>::Pop()
{
  if (st2.size() <= 0)
  {
    if (st1.size() == 0)
    {
      exit(1);
    }
    while ((st1.size() > 0))
    {
      T& top = st1.top();
      st2.push(top);
      st1.pop();
    }
  }

  T head = st2.top();
  st2.pop();
  return head;

}

template <class T>
void SQueue<T>::Push(const T& value)
{
  st1.push(value);
}

int main()
{
  SQueue<int> sq;
  for (int i = 0; i < 10; ++i)
  {
    sq.Push(i);
  }
  for (int i = 0; i < 5; ++i) 
  {
    cout << sq.Pop() << " ";
  }

  for (int i = 0; i < 5; ++i) //分兩次驗證
  {
    cout << sq.Pop() << " ";
  }
  cout << endl;

  system("pause");
  return 0;
}

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

上一篇:C++中小數(shù)點輸出格式(實例代碼)

欄    目:C語言

下一篇:詳解C語言函數(shù)返回值解析

本文標題:數(shù)據(jù)結構用兩個棧實現(xiàn)一個隊列的實例

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1442.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權利,請與我們聯(lián)系,我們將在24小時內進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權所有