日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++?Queue隊列類模版實例詳解_C 語言

作者:諾謙 ? 更新時間: 2022-04-29 編程語言

1.隊列的介紹

隊列的定義

  • 隊列(Queue)是一種線性存儲結構。它有以下幾個特點:
  • 按照"先進先出(FIFO, First-In-First-Out)"方式進出隊列。
  • 隊列只允許在"隊首"進行取出操作(出隊列),在"隊尾"進行插入操作(入隊列?)

隊列實現(xiàn)的方式有兩種

  • 基于動態(tài)數(shù)組實現(xiàn)
  • 基于鏈表形式實現(xiàn)

隊列需要實現(xiàn)的函數(shù)

  • T dequeue() :?出隊列,并返回取出的元素
  • void enqueue(const T &t) :?入隊列
  • T &head() :?獲取隊首數(shù)據(jù),但是不會被取出
  • const T &head() const :?獲取const類型隊首數(shù)據(jù)
  • int length() const:?獲取數(shù)量(父類已經實現(xiàn))
  • void clear():?清空隊列(父類已經實現(xiàn))

2.代碼實現(xiàn)

本章,我們實現(xiàn)的隊列基于鏈表形式實現(xiàn),它的父類是我們之前實現(xiàn)的LinkedList類:

C++?雙向循環(huán)鏈表類模版實例詳解

所以Queue.h代碼如下:

#ifndef QUEUE_H
#define QUEUE_H
#include "throw.h"
// throw.h里面定義了一個ThrowException拋異常的宏,如下所示:
//#include 
//using namespace std;
//#define ThrowException(errMsg)  {cout<<__FILE__<<" LINE"<<__LINE__<<": "<
class Queue : public LinkedList
{
public:
    inline void enqueue(const T &t) { LinkedList::append(t); }
    inline T dequeue()
    {
        if(LinkedList::isEmpty()) {        // 如果棧為空,則拋異常
            ThrowException("Stack is empty ...");
        }
        T t = LinkedList::get(0);
        LinkedList::remove(0);
        return t;
    }
    inline T &head()
    {
        if(LinkedList::isEmpty()) {        // 如果棧為空,則拋異常
            ThrowException("Stack is empty ...");
        }
        return LinkedList::get(0);
    }
    inline const T &head() const
    {
        if(LinkedList::isEmpty()) {        // 如果棧為空,則拋異常
            ThrowException("Stack is empty ...");
        }
        return LinkedList::get(0);
    }
};
#endif // QUEUE_H

3.測試運行

int main(int argc, char *argv[])
{
    Queue queue;
    cout<<"******* current length:"<

運行打印:

總結

原文鏈接:https://blog.csdn.net/qq_37997682/article/details/123127872

欄目分類
最近更新