亲宝软件园·资讯

展开

C++ Queue队列类模版实例

诺谦 人气:0

1.队列的介绍

队列的定义

队列实现的方式有两种

队列需要实现的函数

2.代码实现

本章,我们实现的队列基于链表形式实现,它的父类是我们之前实现的LinkedList类:

C++ 双向循环链表类模版实例详解

所以Queue.h代码如下:

#ifndef QUEUE_H
#define QUEUE_H
#include "throw.h"
// throw.h里面定义了一个ThrowException抛异常的宏,如下所示:
//#include <iostream>
//using namespace std;
//#define ThrowException(errMsg)  {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);}
#include "LinkedList.h"
template < typename T>
class Queue : public LinkedList<T>
{
public:
    inline void enqueue(const T &t) { LinkedList<T>::append(t); }
    inline T dequeue()
    {
        if(LinkedList<T>::isEmpty()) {        // 如果栈为空,则抛异常
            ThrowException("Stack is empty ...");
        }
        T t = LinkedList<T>::get(0);
        LinkedList<T>::remove(0);
        return t;
    }
    inline T &head()
    {
        if(LinkedList<T>::isEmpty()) {        // 如果栈为空,则抛异常
            ThrowException("Stack is empty ...");
        }
        return LinkedList<T>::get(0);
    }
    inline const T &head() const
    {
        if(LinkedList<T>::isEmpty()) {        // 如果栈为空,则抛异常
            ThrowException("Stack is empty ...");
        }
        return LinkedList<T>::get(0);
    }
};
#endif // QUEUE_H

3.测试运行

int main(int argc, char *argv[])
{
    Queue<int> queue;
    cout<<"******* current length:"<<queue.length()<<endl;
    for(int i = 0; i < 5; i++) {
        cout<<"queue.enqueue:"<<i<<endl;
        queue.enqueue(i);
    }
    cout<<"******* current length:"<<queue.length()<<endl;
    while(!queue.isEmpty()) {
        cout<<"queue.dequeue:"<<queue.dequeue()<<endl;
    }
    return 0;
}

运行打印:

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!   

加载全部内容

相关教程
猜你喜欢
用户评论