C++泛化队列

本文介绍了C++中如何实现泛化的队列数据结构,包括使用数组和链表两种方式。通过抽象数据类型ADTqueue定义队列操作,并分别提供了arrayQueue和linkedQueue的实现,配合测试代码展示其功能。
摘要由CSDN通过智能技术生成

队列

队列也是一种特殊的先进先出(FIFO)线性数据结构,数据可以从一端进入,从另一端出去。

队列可以利用数组和链表进行实现。

抽象方法(ADTqueue.h)

/*************************************************************************
> File Name       : ADTqueue.h
> Author          : Harold
> Mail            : 2106562095@qq.com
> Github          : www.github.com/Haroldcc
> Created Time    : 2020年03月05日  10时38分59秒
************************************************************************/
#ifndef ADTQUEUE_H_
#define ADTQUEUE_H_

/***** 队列的抽象数据类型 *****/

template <typename T>
class ADTqueue
{
   
public:
    virtual ~ADTqueue() {
   }
    virtual bool empty() const = 0;
    virtual int size() const = 0;
    virtual T &front() = 0;                  // 返回头元素的引用
    virtual T &back() = 0;                   // 返回尾元素的引用
    virtual void pop() = 0;                  // 删除首元素
    virtual void push(const T &element) = 0; // 元素入队尾
};
#endif

利用数组实现队列(arrayQueue.h)

/*************************************************************************
> File Name       : arrayQueue.h
> Author          : Harold
> Mail            : 2106562095@qq.com
> Github          : www.github.com/Haroldcc
> Created Time    : 2020年03月05日  10时48分43秒
************************************************************************/
#ifndef ARRAYQUEUE_H_
#define ARRAYQUEUE_H_

/***** 运用数组实现队列 *****/
#include "ADTqueue.h"
#include "./myExceptions.h"
#include <sstream>
#include <iostream>

template <typename T>
class arrayQueue : public ADTqueue<T>
{
   
private:
    int m_front; // 队头
    int m_back;  // 队尾
    int m_arrayLength;
    T *m_queue;

public:
    arrayQueue(int initialCapacity = 10);
    ~arrayQueue() {
    delete[] m_queue; }

    bool empty() const {
    return m_front == m_back; }
    int size() const {
    return (m_back - m_front + m_arrayLength) % m_arrayLength; }
    T &front()
    {
   
        if (m_front == m_back)
        {
   
            throw queueEmpty();
        }
        return m_queue[(m_front + 1) % m_arrayLength];
    }
    T &back()
    {
   
        if (m_front == m_back)
        {
   
            throw queueEmpty();
        }
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值