一、队列(FIFO-first in first out)
- 分类:
- 普通队列: 先进先出,读取时有两种:一种是指针移动向下读取;一种是每读取一个元素,后面的所有元素自动向前移动一个位置。
- 这两种办法都有缺点。第一种会造成出栈后的数据的位置没有被重新利用,内存浪费。第二种是每次读出一个元素,后面所有元素都前进移动,效率低下。
- 环形队列: 预先设定环形队列可容纳值的大小,分头指针和尾指针指示队列的头和尾。存储时存在尾指针位置,然后尾指针加一。读取时读头指针位置,头指针加一。这样所有的空间可以循环利用。利用判空或判满函数来决定队列是否还有元素或者队列是否已满。
- 缺点是队列大小不可变,如果队列满了,就不能再加入新元素。但是效率高,空间利用同样高效。
- Note that:
- 新建类对象在创建该类型的数组时,为防止报错,需要给构造函数里的元素赋初值
环形队列实现代码
#pragma once
#include<iostream>
using namespace std;
template<class T>
class Myqueue
{
public:
Myqueue(int num);
void addIngre(T m);
void deleIngre();
int IngreNum();
bool queueFull();
void clearIngre();
bool queueEmpty();
void queueTraverse();
~Myqueue();
private:
int m_iNum;
T* m_tArray;
int m_iHead;
int m_iTail;
int m_iSize;
};
template<class T>
Myqueue<T>::Myqueue(int num)
{
clearIngre();
m_iSize = num;
m_tArray = new T[m_iSize];
}
template<class T>
Myqueue<T>::~Myqueue()
{
delete[]m_tArray;
m_tArray = NULL;
}
template<class T>
void Myqueue<T>::addIngre(T m)
{
if (!queueFull())
{
m_iNum++;
m_iTail = m_iTail % m_iSize;
m_tArray[m_iTail] = m;
m_iTail++;
}
else
{
cout << "Can not add any more ingredients!" << endl;
}
}
template<class T>
void Myqueue<T>::deleIngre()
{
if (!queueEmpty())
{
m_iNum--;
cout <<"被消除的首元素为:"<< m_tArray[m_iHead] << endl;
m_iHead++;
m_iHead = m_iHead % m_iSize;
}
else
{
cout << "There is no ingredient!" << endl;
}
}
template<class T>
int Myqueue<T>::IngreNum()
{
cout << "当前元素个数为:" <<m_iNum<< endl;
return m_iNum;
}
template<class T>
void Myqueue<T>::clearIngre()
{
m_iNum = 0;
m_iTail = m_iHead = 0;
cout << "当前元素个数为:" << m_iNum << endl;
}
template<class T>
bool Myqueue<T>::queueEmpty()
{
return m_iNum == 0 ? true : false;
}
template<class T>
bool Myqueue<T>::queueFull()
{
return m_iNum == m_iSize ? true : false;
}
template<class T>
void Myqueue<T>::queueTraverse()
{
for (int i = m_iHead; i < m_iNum + m_iHead; i++)
{
i = i % m_iSize;
cout << m_tArray[i] << endl;
}
}
#pragma once
#include<iostream>
using namespace std;
#include<string>
class customer
{
friend ostream& operator<<(ostream& out, customer& c)
{
out << "Name:"<<c.name<<","<<"Age:" << c.age;
return out;
}
public:
customer(string n="陈胖鹿",int a=4);
~customer();
customer& operator=(customer& m)
{
this->name = m.name;
this->age = m.age;
return *this;
}
private:
string name;
int age;
};
#include"customer.h"
customer::customer(string n, int a):name(n),age(a)
{
}
customer::~customer()
{
}
#include"Myqueue.h"
#include<string>
#include"customer.h"
int main()
{
Myqueue<customer> * p = new Myqueue<customer>(4);
customer c1("张三",43);
customer c2("张四", 44);
customer c3("张五", 46);
p->addIngre(c1);
p->addIngre(c2);
p->addIngre(c3);
p->queueTraverse();
cout << endl;
p->deleIngre();
p->deleIngre();
p->deleIngre();
p->IngreNum();
delete p;
p = NULL;
return 0;
}
Higher you climb, more view you will see.