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

来源:互联网 发布:无线路由里访客网络 编辑:程序博客网 时间:2024/06/04 17:50

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

链队列实现

  1. 头文件定义在LinkQueue.h:
#ifndef LINKQUEUE_H_INCLUDED#define LINKQUEUE_H_INCLUDEDusing 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. 运行结果

    这里写图片描述

应用

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

阅读全文
0 0
原创粉丝点击