基于循环数组的队列实现遇阻,求排查代码错误
循环数组队列实现问题排查
需求说明
enqueue()函数:入队前队列未满则执行入队并返回true;队列已满则返回false,且不执行入队操作。dequeue()函数:队列非空时返回出队元素,空队列则返回0。
不可修改的头文件(IntegerArrayQueue.h)
#pragma once #include <iostream> using namespace std; class IntegerArrayQueue { private: int* array; //pointer to array of integers int front; //index of item to dequeue int back; //index of item to enqueue int size; public: IntegerArrayQueue() : array(new int[10]), front(0), back(9), size(10) { for (int i = 0; i<10; i++) array[i]=0; } IntegerArrayQueue(int size) : array(new int[size]), front(0), back(size-1), size(size) { for (int i = 0; i<size; i++) array[i]=0; } ~IntegerArrayQueue() { delete [] array;} void printArrayQueue() { for (int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; cout << "front: " << front << endl; cout << "back: " << back << endl; cout << "size: " << size << endl; } //Implement the enqueue and dequeue functions //enqueue: if there is space available enqueue value and //return true, otherwise return false bool enqueue(int value); //dequeue: if there is a value at the front of the queue //return the value and remove from the queue, //otherwise return 0 int dequeue(); };
待排查的实现代码(IntegerArrayQueue.cpp)
#include "IntegerArrayQueue.h" bool IntegerArrayQueue::enqueue(int value) { if ((back + 1) % size == front) { return false; } else { back = (back + 1) % size; array[back] = value; return true; } } int IntegerArrayQueue::dequeue() { if (front == 0) { return 0; } else { int val = array[front]; if (front == back) { front = 0; back = 0; } else { front = (front) % size; } return val; } }
代码错误分析
1. dequeue()的空队列判断逻辑错误
原代码用front == 0判断空队列,完全不符合循环队列的设计逻辑。根据头文件的初始化规则,空队列的状态是(back + 1) % size == front(比如默认构造中back=9,size=10,(9+1)%10=0 == front=0),必须用这个条件判断队列是否为空。
2. dequeue()的队头移动逻辑错误
原代码中front = (front) % size没有让队头前进,正确写法应该是front = (front + 1) % size,这样才能指向队列的下一个元素,完成出队后的队头更新。
3. dequeue()的清空队列逻辑错误
当队列只剩最后一个元素(front == back)时,出队后应该恢复到初始的空队列状态:front=0,back=size-1,而不是front=0、back=0,否则会破坏后续的空/满队列判断逻辑。
修正后的dequeue()实现
int IntegerArrayQueue::dequeue() { // 判断队列是否为空 if ((back + 1) % size == front) { return 0; } int val = array[front]; // 队列只剩一个元素,恢复初始空状态 if (front == back) { front = 0; back = size - 1; } else { front = (front + 1) % size; } return val; }
内容的提问来源于stack exchange,提问作者akap04
相关产品推荐
相关产品推荐

