0

我正在按照大学的要求学习数据结构。我已经使用动态数组实现了队列 DS,但它不知何故不起作用。它更新第一个入队方法调用的值,但从第二个调用开始,它什么也不做。

我的代码

#include <iostream>
#define MAXSIZE 8

class Queue
{
private:
    int *arr;
    int front;
    int rear;
    int itemsCount;

public:
    Queue()
    {      
        arr = new int[MAXSIZE];
        front = -1;
        rear = -1;
        itemsCount = 0;
    }

    ~Queue()
    {
        delete[] arr;
    }

    int dequeue()
    {

        int x = arr[front];
        front = (front + 1) % MAXSIZE;
        itemsCount--;
        return x;
    }

    void enqueue(int x)
    {
        if (empty())
        {
            front++;
        }

        rear = (rear + 1) % MAXSIZE;
        arr[rear] = x;
        itemsCount++;
    }

    bool full() const
    {
        if (itemsCount == MAXSIZE)
            return true;
        return false;
    }

    bool empty() const
    {
        if (itemsCount == 0)
            return true;
        return false;
    }
};

int main(int argc, char const *argv[])
{
    Queue myQ;

    myQ.enqueue(11);
    myQ.enqueue(22); // This doesn't update the array at 1th index
    myQ.enqueue(33);
    myQ.enqueue(44);
    myQ.enqueue(55);
    myQ.enqueue(66);
    myQ.enqueue(77);
    myQ.enqueue(88);

    std::cout << myQ.dequeue() << std::endl;

    return 0;
}

PS 我知道实现是不完整的,我还没有处理所有的边缘情况。那是因为我无法正常工作。

PPS 它适用于静态数组。但不是动态分配的。

4

1 回答 1

0

显然,当我执行出队操作并在屏幕上显示值时,数组正在更新并且程序正在运行。但是调试器不知何故只显示了动态分配数组的第一个索引处的值。

数组指针

于 2021-12-13T23:46:14.877 回答