前面我们实现了队列的顺序存储结构的一般功能。并用循环列表使取第一个元素的时间复杂度从O(n)降到了O(1)。一般来说,当我们已知队列的最大可能长度时,用顺序存储结构实现,因为可以减少链式存储结构中寻址时间开销。但当我们不知道具体长度时,为了避免内存的浪费或者内存不够的情况,一般我们选择链式存储结构。
主要函数介绍:
本例实现中,利用了结构体存储节点信息。并利用了函数模板实现了队列链式存储结构的实例化过程。以下为主要的结构和函数定义:
struct Node //利用结构体定义节点信息
{
T data;
Node * next;
};
template<typename T>
class Queue //定义队列链式模板类
{
private:
Node<T> *front; //指向头结点的指针
Node<T> *rear; //指向尾节点的指针
int length; //队列长度
public:
Queue(); //构造函数
bool InQueue(T &e); //队列中插入数据e
T OutQueue(); //队列中取出数据
bool isEmpty() const; //判断队列是否为空
int Length() const; //队列的长度
};
//值得注意的是在构造函数对对象进行实例化时,需要为头结点开辟一个内存,并将首尾指针都指向头结点。否则默认情况下,首尾节点都为nullprt。
使用示例输出:
Enter the arrival customer name:
vbdf
There have 1 customers.
Enter the arrival customer name:
bsdf
There have 2 customers.
Enter the arrival customer name:
bsdf
There have 3 customers.
vbdf leave, and 2 people remain.
bsdf leave, and 1 people remain.
bsdf leave, and 0 people remain.
队列的链式存储结构头文件
#pragma once
#ifndef QUEUEV2_H_
#define QUEUEV2_H_
template<typename T>
struct Node
{
T data;
Node * next;
};
template<typename T>
class Queue
{
private:
Node<T> *front;
Node<T> *rear;
int length;
public:
Queue();
bool InQueue(T &e);
T OutQueue();
bool isEmpty() const;
int Length() const;
};
template<typename T>
Queue<T>::Queue()
{
Node<T> * p = new Node<T>;
front = rear = p;
length = 0;
}
template<typename T>
bool Queue<T>::InQueue(T &e)
{
Node<T> *p = new Node<T>;
p->data = e;
p->next = nullptr;
rear->next = p;
rear = p;
length++;
return true;
}
template<typename T>
T Queue<T>::OutQueue()
{
Node<T> *p = front->next;
if (p->next == nullptr) {
rear = front;
T out = p->data;
delete p;
length--;
return out;
}
else if (isEmpty())
{
cout << "The queue is empty!!!" << endl;
exit(EXIT_FAILURE);
}
else
{
front->next = p->next;
T out = p->data;
delete p;
length--;
return out;
}
}
template<typename T>
bool Queue<T>::isEmpty() const
{
return(front == rear);
}
template<typename T>
int Queue<T>::Length() const
{
return length;
}
#endif // !QUEUEV2_H_
队列的链式存储结构使用示例:
#include<iostream>
#include<string>
#include"queuev2.h"
using namespace std;
void main()
{
Queue<string> test;
for (int i = 0; i < 3;i++) {
cout << "Enter the arrival customer name: \n";
string name;
getline(cin, name);
test.InQueue(name);
cout << "There have " << test.Length() << " customers.\n\n";
}
while (!test.isEmpty()) {
cout << test.OutQueue() << " leave, and ";
cout << test.Length() << " people remain.\n";
}
}