如何在队列元素定位方法中用布尔变量退出while循环?
队列元素定位方法死循环问题修复
问题描述
实现了一个队列元素定位方法,通过遍历队列查找指定元素的位置,但运行时出现死循环,计数器持续递增直至手动终止程序。已声明布尔变量found,但不清楚如何用它终止循环。相关代码如下:
类成员变量代码段
public class LinkedQueue<T> implements QueueADT<T> { boolean found=false; private int n; private LinearNode<T> first, last; private LinearNode<T> T; }
定位方法代码
public int position(T element) throws EmptyQueueException, NoSuchElementException { if (isEmpty()) { throw new EmptyQueueException("Queue is empty"); } LinearNode<T> node = first; n = 0; while (node != null) { if (node.getElement().equals(element)) { found = true; System.out.println(n); } n++; node.getNext(); } return n; }
运行时死循环,终止前计数器输出片段:
142215 142216 142217 142218 142219 142220 BUILD STOPPED (total time: 3 seconds)
问题根源
- 节点未更新:
node.getNext()仅获取下一个节点,但未将值赋值给node,导致node始终指向队列首节点,永远不为null,循环无法结束。 - 找到元素未终止:即使匹配到目标元素,循环仍会继续遍历,且未利用
found变量触发终止逻辑。 - 变量作用域不合理:
found和n作为类成员变量,会导致多次调用方法时状态污染。
修复后的代码
public class LinkedQueue<T> implements QueueADT<T> { private LinearNode<T> first, last; // 移除不必要的成员变量:found、n、命名冲突的T } public int position(T element) throws EmptyQueueException, NoSuchElementException { if (isEmpty()) { throw new EmptyQueueException("Queue is empty"); } LinearNode<T> node = first; int n = 0; // 方法内声明计数器,避免跨调用状态干扰 boolean found = false; // 方法内声明状态变量 // 循环条件:节点未到末尾 且 未找到目标元素 while (node != null && !found) { if (node.getElement().equals(element)) { found = true; return n; // 找到元素直接返回位置,无需继续遍历 } n++; node = node.getNext(); // 关键:更新节点为下一个元素,推进遍历 } // 遍历完成未找到元素,抛出对应异常 throw new NoSuchElementException("Element not found in queue"); }
修复说明
- 解决死循环:通过
node = node.getNext()更新遍历节点,确保队列遍历到末尾时node变为null,循环正常终止。 - 利用found终止循环:在
while条件中加入!found,一旦找到目标元素,循环立即停止。 - 优化返回逻辑:找到元素时直接返回位置,减少不必要的遍历操作。
- 规范变量作用域:将
found和n改为方法内部变量,避免多调用场景下的状态混乱。 - 完善异常处理:未找到元素时抛出
NoSuchElementException,符合方法声明的异常约定。
内容的提问来源于stack exchange,提问作者stackover
相关产品推荐
相关产品推荐

