EnQueue 方法在循环队列中未正确返回C++?

EnQueue method not returning correctly in C++ circular queue?

本文关键字:返回 C++ 方法 循环 队列 EnQueue      更新时间:2023-10-16

我只有不到 3 个月的编码经验,所以我开始使用 LeetCode 来构建超出学校分配的代码时间。

我正在努力尝试构建一个循环队列 (FIFO(,但它无法编译。我收到以下错误,我被难住了:

解决方案.cpp:在成员函数 enQueue 中 第 58 行:字符 2:错误:控制到达非无效函数的末尾 [-werror=返回类型] }

一件事:我被特别指示不要使用 std::queue 库,所以虽然我知道这可能会容易得多,但这不是一个选择。

我构建的完整代码如下:

class MyCircularQueue
{
private:
int* data = nullptr;
int size;
int capacity;
int front_p;
int rear_p;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k)
{
data = new int[k];
size = 0;
capacity = k;
front_p = 0;
rear_p = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value)
{
if (!isFull() && isEmpty())
{
for (int i = 0; i < capacity; i++)
{
if (data[i] == 0)
{
data[i] = value;
size++;
front_p = data[i];
rear_p = data[i];
return true;
}
}
}
else if (!isFull())
{
for (int i = 0; i < capacity; i++)
{
if (data[i] == 0)
{
data[i] = value;
size++;
front_p = data[i];
rear_p = rear_p++;
return true;
}
}
}
else
{
return false;
}
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue()
{
if (isEmpty())
{
return false;
}
else
{
front_p = front_p++;
return true;
}
}
/** Get the front item from the queue. */
int Front()
{
return front_p;
}
/** Get the last item from the queue. */
int Rear()
{
return rear_p;
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty()
{
for (int i = 0; i < size; i++)
{
if (data[i] != 0)
{
return false;
}
else
return true;
}
}
/** Checks whether the circular queue is full or not. */
bool isFull()
{
if (size == capacity)
{
return true;
}
else
return false;
}
};

您收到该错误是因为通过enQueue执行并不总是以return语句结束。 从逻辑上讲,这可能永远不会发生,但编译器不知道这一点,因为它看到如果其中一个for循环以i >= capacity终止,您将不会遇到return语句。

简单的解决方法是删除最后一个else,以便return false;始终在函数结束时执行。

}
return false;
}