我正在按照大学的要求学习数据结构。我已经使用动态数组实现了队列 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 它适用于静态数组。但不是动态分配的。