Java LinkedList手动实现问题:添加元素值被覆盖如何修复?
修复Java自定义LinkedList添加元素丢失问题
你的自定义LinkedList出现添加元素后无法正确遍历的问题,核心原因是**add方法直接修改了链表的head指针**,导致链表的头节点引用丢失,原有元素无法被访问。此外remove方法和测试代码也存在逻辑问题,下面逐一说明并修复:
1. add方法的核心错误
你在add方法的else分支中,直接用head进行遍历并移动指针:
while (head.next != null) { head = head.next; } head.next = node;
每次添加元素时,head都会被移动到链表的最后一个节点,这会导致原来的头节点彻底丢失。后续遍历链表时,head已经不是真正的表头,自然无法访问之前添加的元素。
修复后的add方法
使用临时变量current遍历链表,保留head指针始终指向表头:
public void add(int value) { Node node = new Node(value); if (head == null) { head = node; } else { Node current = head; // 用临时变量遍历,不修改原head指针 while (current.next != null) { current = current.next; } current.next = node; } }
2. remove方法的问题及修复
你的remove方法存在两个明显问题:
- 不必要创建新的
LinkedListM对象,完全无用 - 删除节点后直接移动
dummy指针,会跳过下一个节点的检查(比如连续重复元素的场景)
修复后的remove方法
public void remove(int value) { Node dummy = new Node(0); dummy.next = head; Node current = dummy; // 用current遍历,保留dummy用于更新表头 while (current.next != null) { if (current.next.value == value) { // 跳过待删除节点,完成删除操作 current.next = current.next.next; // 删除后不移动current,避免跳过下一个节点的检查 } else { // 只有未删除节点时才移动指针 current = current.next; } } // 更新表头(如果删除的是原头节点) head = dummy.next; }
3. 测试代码的问题及修复
测试代码中直接修改了ll.head,遍历后原链表的头指针会被破坏;同时循环条件head.next != null会导致最后一个元素无法打印。
修复后的测试代码
使用临时变量遍历,不修改原链表的head指针:
public class p { public static void main(String[] args) { LinkedListM ll = new LinkedListM(); ll.add(1); ll.add(2); ll.add(3); ll.add(4); ll.add(5); // 用临时变量current遍历,保留原head指针 Node current = ll.head; while (current != null) { System.out.print(current.value); if (current.next != null) { System.out.print(" -> "); } current = current.next; } System.out.println(); // 测试remove功能 ll.remove(3); current = ll.head; while (current != null) { System.out.print(current.value); if (current.next != null) { System.out.print(" -> "); } current = current.next; } } }
修复后运行结果
添加元素后遍历输出:
1 -> 2 -> 3 -> 4 -> 5
删除3后遍历输出:
1 -> 2 -> 4 -> 5
内容的提问来源于stack exchange,提问作者learnbasic
相关产品推荐
相关产品推荐

