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

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");
}

版权声明:本文为qq_28314759原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。