数组实现Queue的删除逻辑错误排查请求
问题定位与修复方案
我一眼就发现了导致队列删除后异常为空的原因——你的Remove函数里存在一个赋值/相等判断混淆的经典低级错误!
错误根源
在Remove函数的这个判断逻辑里:
if (front = rear) { front = rear = -1; }
你把相等比较运算符==误写成了赋值运算符=。当插入1、2、3后,front=0,rear=2:
- 执行
front = rear时,会把rear的值(2)赋给front,此时front直接变成2 - 这个赋值表达式的结果是2(非零值),在C++中会被视为
true,于是触发front = rear = -1的逻辑,直接把整个队列的首尾指针重置为空状态 - 这就是为什么删除第一个元素后,队列直接显示为空的核心原因
修复后的完整代码
只需要把Remove函数里的赋值操作改成相等判断即可,我也顺带优化了空队列时的提示信息:
#include<iostream> #include<conio.h> using namespace std; int Remove(int[]); int Insert(int[], int); void Display(int[], int, int); int front = -1, rear = -1; void main() { const int size = 50; int Q[size]; int item, res; char ch = 'y'; while (ch == 'y' || ch == 'Y') { cout << "\n Enter item for insertion : "; cin >> item; res = Insert(Q, item); if (res == -1) { cout << "\n OVERFLOW!"; _getch(); } cout << "\n Now the Queue is : "; Display(Q, front, rear); cout << "\n Do you wish to insert more elements into the array(y/n)? : "; cin >> ch; } cout << "\n Now the deletion of elements from the Queue begins...."; ch = 'y'; while (ch == 'y' || ch == 'Y') { res = Remove(Q); if (res == -1) { cout << "\n UNDERFLOW!"; _getch(); } else { cout << "\n The element deleted from the Queue is : " << res << endl; cout << "\n Now, the Queue(Front--to--Rear) is : "; Display(Q, front, rear); } cout << "\n Do you wish to delete more elements from the Queue(y/n)? : "; cin >> ch; } _getch(); return; } int Insert(int Q[], int ele) { const int size = 50; if (rear == size - 1) { return -1; } else { if (rear == -1) { front = rear = 0; Q[rear] = ele; } else { rear++; Q[rear] = ele; } return 0; } } // 修复后的Remove函数 int Remove(int Q[]) { int ret; if (front == -1) { return -1; } else { ret = Q[front]; // 把赋值运算符=改为相等判断运算符== if (front == rear) { front = rear = -1; } else { front++; } } return ret; } void Display(int Q[], int front, int rear) { if (front == -1) { cout << "Empty Queue"; return; } for (int i = front; i < rear; i++) { cout << Q[i] << " <- "; } cout << Q[rear] << endl; }
验证效果
插入1、2、3后执行第一次删除操作:
- 会正确返回元素1,
front变为1,rear保持为2 - Display函数会输出
2 <- 3,完全符合队列FIFO的预期行为
内容的提问来源于stack exchange,提问作者Amap
相关产品推荐
相关产品推荐

