链式队列

链式队列

队列实际上也是一种线性存储结构,它的特点是进队总是在队尾,出队总是在队头。参考实际生活中的买票排队过程非常容易理解。这里用链表实现了队列。


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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值