C++队列实现(链表)

队列的概念

通俗的说,队列类似于我们日常生活中的排队,这个数据结构与栈不同,栈是先进后出(类似于弹匣),而队列是先进先出。
此处引用百度百科对于队列的定义:队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

创建一个队列类

创建一个链表组成的队列类,我们需要先建立一个链表:

typedef struct Node {
    int data;
    struct Node* next;
}* node, list;

接着,我们需要建立一个Queue类,创建队头和队尾指针,以及对应的构造方法:

class Queue {
private:
    node head;
    node tail;
    int size;
public:
    Queue();
    void push(int x) ;
    void pop() ;
    int front();
    bool isEmpty() ;
    ~Queue();
};

接下来我们需要实现队列中的部分功能:
构造函数:

Queue() {
       size=0;
       head=tail=nullptr;
   }

入队操作:

void push(int x) {
       if(size==0){
           head->next=head=tail=(node)malloc(sizeof(list));
           head->data=tail->data=x;
       }else if(size==1){
           head->next=tail=(node)malloc(sizeof(list));
           tail->data=x;
           tail->next=nullptr;
       }else{
           tail->next=(node)malloc(sizeof(list));
           tail->next->data=x;
           tail=tail->next;
       }
       size++;
   }

这里我们需要分情况讨论:
1.没有元素在队列中的情况下,我们的head指针和tail指针此时是相同的指针,我们此时开辟一个空间,让head和tail同时指向这个唯一元素;
2.只有一个元素在的情况下,此时我们再次添加元素,head和tail就要分开表示其对应的元素,我们将新元素插入队尾;
3.在两个元素以上的情况下,我们只需要对队尾进行插入就可以了。

出队操作:

void pop() {
        node p = head;
        head=head->next;
        free(p);
        size--;
    }

出队操作和栈类似,只需要把头结点后移即可。

获取队首元素:

int front() {
        return head->data;
    }

判断队列是否非空:

bool isEmpty() {
        return size==0;
    }

至此,队列类已经完全创建,此处省略测试代码

完整代码

#include <cstdlib>
#include <iostream>
using namespace std;
typedef struct Node {
    int data;
    struct Node* next;
}* node, list;
class Queue {
private:
    node head;
    node tail;
    int size;
public:
    Queue() {
        size=0;
        head=tail=nullptr;
    }
    void push(int x) {
        if(size==0){
            head->next=head=tail=(node)malloc(sizeof(list));
            head->data=tail->data=x;
        }else if(size==1){
            head->next=tail=(node)malloc(sizeof(list));
            tail->data=x;
            tail->next=nullptr;
        }else{
            tail->next=(node)malloc(sizeof(list));
            tail->next->data=x;
            tail=tail->next;
        }
        size++;
    }
    void pop() {
        node p = head;
        head=head->next;
        free(p);
        size--;
    }
    int front() {
        return head->data;
    }
    bool isEmpty() {
        return size==0;
    }
};

若代码有错误或者可以优化,请大佬不胜赐教,多多指点,谢谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值