链队列的C++实现及其应用

队列是先进先出的数据结构,符合世间万物先到先得的处理顺序。本文将列出如何实现队列。本文使用链表加上头指针和尾指针构成了队列,其中头指针指向队头元素的上一个节点(头结点),尾指针指向队尾元素。

链队列实现

  1. 头文件定义在LinkQueue.h:
#ifndef LINKQUEUE_H_INCLUDED
#define LINKQUEUE_H_INCLUDED
using Type = int;
typedef struct node{
    Type data;
    node *next;
}node,*nodePtr;

class LinkQueue {
private:
    nodePtr front;
    nodePtr rear;
public:
    LinkQueue();
    bool DestroyQueue();
    bool ClearQueue();
    bool isEmpty();
    int length();
    bool getHead(Type &e);
    bool push(Type &e);
    bool pop(Type &e);
};
#endif // LINKQUEUE_H_INCLUDED
  1. 具体函数定义在LinkQueue.cpp:
#include "LinkQueue.h"
LinkQueue::LinkQueue(){
    front = rear = new node;
    front->next = nullptr;
}
bool LinkQueue::DestroyQueue(){
    while(front){
        rear = front->next;
        delete front;
        front = rear;
    }
    return true;
}
bool LinkQueue::ClearQueue(){
    nodePtr t;
    t = front;
    front=front->next;
    DestroyQueue();
    front=rear=t;
    front->next=nullptr;
}

bool LinkQueue::isEmpty(){
    return front==rear?true:false;
}
int LinkQueue::length(){
    int cnt = 0;
    nodePtr t =front;
    while(t != rear){
        ++cnt;
        t = t->next;
    }
    return cnt;
}
bool LinkQueue::getHead(Type &e){
    if(isEmpty())
        return false;
    e = front->next->data;
}
bool LinkQueue::push(Type &e){
    nodePtr t = new node;
    t->data = e;
    t->next = nullptr;
    rear->next = t;
    rear = t;
}
bool LinkQueue::pop(Type &e){
   if(isEmpty())
        return false;
   nodePtr t = front->next;
   e = t->data;
   front->next=t->next;
   if(rear==t)
        rear =front;
   return true;
}


  1. 主函数(main.cpp):
#include <iostream>
#include "LinkQueue.h"
using namespace std;

int main()
{
    LinkQueue q;
    Type e=1;
    q.push(e);
    e=2;
    q.push(e);
    q.pop(e);
    cout<<e<<' ';
    e=3;
    q.push(e);
    e=4;
    q.push(e);
    q.pop(e);
    cout<<e<<' ';
    q.pop(e);
    cout<<e<<' ';
    q.pop(e);
    cout<<e<<' ';
    return 0;
}
  1. 运行结果

    这里写图片描述

应用

队列一般应用在计算过程按层次性顺序进行的场景,比如层次遍历树、调度算法等。具体将会在讲到树的时候提到。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值