队列
队列也是一种特殊的先进先出(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();
}