【C++数据结构】数组循环队列的实现

本文介绍了一个简单的队列数据结构的实现方法,并通过C++代码示例展示了如何使用队列进行元素的入队和出队操作,同时包含了队列是否为空及满的判断逻辑。

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

Queue.h

#pragma once
class Queue
{
private:
    int MaxSize = 10;
    int *queue;
private:
    int front = 0;
    int rear = 0;

public:
    Queue();
    ~Queue();
private:
    bool isEmpty(void);
    bool isFull(void);

public:
    void InQueue(int);
    void OutQueue(void);
    void Display(void);
};

Queue.cpp

#include "Queue.h"
#include <iostream>


Queue::Queue()
{
    queue = new int[10];
}


Queue::~Queue()
{
    delete queue;
    queue = nullptr;
}

bool Queue::isEmpty(void)
{
    if (front == rear)
    {
        return true;
    }
    else if (rear + 1 == MaxSize&&front == 0)
    {
        return true;
    }
    return false;
}

bool Queue::isFull(void)
{
    if (rear == front+1)
    {
        return true;
    }
    else if (front+1 == MaxSize&&rear==0)
    {
        return true;
    }
    return false;
}

void Queue::InQueue(int data)
{
    if (isFull())
    {
        return;
    }

    queue[front] = data;
    front++;
    if (front == MaxSize)
    {
        front = 0;
    }
}

void Queue::OutQueue(void)
{
    if (isEmpty())
    {
        return;
    }
    rear++;
    if (rear == MaxSize)
    {
        rear = 0;
    }
}

void Queue::Display(void)
{
    int f, r;
    f = front;
    r = rear;
    while (f!=r)
    {
        std::cout << queue[r] << std::endl;
        r++;
        if (r == MaxSize)
        {
            r = 0;
        }
    }
}   

main.cpp

void main()
{
    Queue q;
    for (int index = 0; index < 10; index++)
    {
        q.InQueue(index);
    }
    for (int index = 0; index < 5; index++)
    {
        q.OutQueue();
    }
    for (int index = 0; index < 2; index++)
    {
        q.InQueue(index);
    }
    for (int index = 0; index < 2; index++)
    {
        q.OutQueue();
    }
    q.Display();

    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值