C++实现队列操作(顺序存储和链式存储)

本文展示了如何使用链式存储和顺序存储结构实现队列的初始化、入队、出队操作。顺序存储队列在满时通过动态扩容保持功能;链式存储队列则利用节点动态创建与删除。程序包括了对两种队列结构的完整实现,并在主函数中进行了测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、任务描述:编写函数,采用链式存储和顺序存储实现队列的初始化、入队、出队操作

2、亮点:
①对于顺序操作增添了函数IsFull(),用来判断队列有没有满,如果满了就重新分配空间
②由于存在分配在堆上的资源,实现了析构函数

3、运行情况:
在这里插入图片描述
4、源代码:

#include <iostream>

#define QueueElemType int
using namespace std;

class Queue {

private:
    QueueElemType* Q;
    int front = 0;
    int rear = 0;
    int length = 3;

public:
    Queue() {
        Q = new int[length];
    }

    void CheckFull() {
        if (rear < length && rear - front + 1 < length)
            return;
        QueueElemType* p = new int[length * 2];
        int i = front, j = 0;

        while (i <= rear) {
            p[j++] = Q[i++];
        }

        delete[]Q;
        Q = p;
        front = 0;
        rear = j - 1;
        length *= 2;
    }

    void InQueue(QueueElemType e) {
        CheckFull();
        Q[rear++] = e;
    }

    void OutQueue() {

        if (rear == front) {
            cout << "队列为空!" << endl;
            return;
        }
        cout << Q[front++] << " ";
    }
    ~Queue() {
        delete[] Q;
    }
};

class LinkedQueue {
private:

    class QNode{
    public:
        QueueElemType date;
        QNode* next;
    };

    QNode* front = NULL;
    QNode* rear = NULL;

public:
    void InQueue(QueueElemType e) {
        if (NULL == front) {
            rear = front = new QNode;    
        }
        else {
            rear->next = new QNode;
            rear = rear->next;
        }
        rear->date = e;
        rear->next = NULL;
    }

    void OutQueue() {
        if (NULL == rear) {
            cout << "队列为空!" << endl;
            return;
        }
        cout << front->date << " ";
        front = front->next;
    }

    ~LinkedQueue() {

        QNode* p = front;
        
        while (NULL != p) {
            front = front->next;
            delete p;
            p = front;
        }
    }
};

int main()
{

    Queue Q;
    for (int i = 0; i < 10; i++)
        Q.InQueue(i);
    for (int i = 0; i < 5; i++)
        Q.OutQueue();
    for (int i = 0; i < 5; i++)
        Q.InQueue(i+10);
    for (int i = 0; i < 10; i++)
        Q.OutQueue();

    cout << endl << endl;
    LinkedQueue LQ;
    for (int i = 0; i < 10; i++)
        LQ.InQueue(i);
    for (int i = 0; i < 5; i++)
        LQ.OutQueue();
    for (int i = 0; i < 5; i++)
        LQ.InQueue(i + 10);
    for (int i = 0; i < 10; i++)
        LQ.OutQueue();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值