链式队列
队列实际上也是一种线性存储结构,它的特点是进队总是在队尾,出队总是在队头。参考实际生活中的买票排队过程非常容易理解。这里用链表实现了队列。
1.定义结点类
struct QueueNode
{
int data;
QueueNode *next;
QueueNode(int x = 0xFFFF)
:data(x), next(nullptr) {}
};
2.定义队列类
class LinkedQueue
{
public:
LinkedQueue();
~LinkedQueue();
void QueueClear();
bool IsEmpty();
int GetHead();
void QueueInsert(int e);
void QueuePop();
int GetLength();
void QueuePrint();
private:
QueueNode *front;
QueueNode *rear;
int QueueLength;
};
QueueClear 方法:清空整个队列;
IsEmpty 方法:判断队列是否为空;
GetHead 方法:得到队首元素;
QueueInsert 方法:进队方法;
QueuePop 方法:出队方法;
GetLength 方法:计算队长;
QueuePrint 方法:打印队列。
3.方法实现
#include "queue.h"
#include <iostream>
LinkedQueue::LinkedQueue()
{
this->front = this->rear = new QueueNode();
this->QueueLength = 0;
}
LinkedQueue::~LinkedQueue()
{
this->QueueClear();
delete this->front;
delete this->rear;
}
void LinkedQueue::QueueClear()
{
if (this->IsEmpty())
{
return;
}
QueueNode *p = this->front->next;
QueueNode *tmp = p;
this->rear = this->front;
while (p)
{
p = p->next;
delete tmp;
tmp = p;
}
this->QueueLength = 0;
}
bool LinkedQueue::IsEmpty()
{
return this->front == this->rear;
}
int LinkedQueue::GetHead()
{
if (this->IsEmpty())
{
return 0xFFFF;
}
return this->front->next->data;
}
void LinkedQueue::QueueInsert(int e)
{
QueueNode *p = new QueueNode(e);
this->rear->next = p;
this->rear = p;
this->QueueLength += 1;
}
void LinkedQueue::QueuePop()
{
if (this->IsEmpty())
{
std::cout << "EmptyQueue" << std::endl;
}
QueueNode *p = this->front->next;
this->front->next = p->next;
delete p;
this->QueueLength -= 1;
}
int LinkedQueue::GetLength()
{
return this->QueueLength;
}
void LinkedQueue::QueuePrint()
{
if (this->IsEmpty())
{
std::cout << 0xFFFF << std::endl;
return;
}
QueueNode *p = new QueueNode();
p = this->front->next;
while (p->next)
{
std::cout << p->data << "<=";
p = p->next;
}
std::cout << p->data << std::endl;
}