单链表问题:将尾节点移至首节点之后
修复链表尾节点移至首节点后的问题
你的需求是把链表的尾节点移到首节点之后(比如1->2->3->4->5变成1->5->2->3->4),咱们来一步步排查代码里的问题,然后修正它。
你的代码核心问题分析
先看Manipulate方法的逻辑:
public void Manipulate(){ Node curr = head; Node next = null; Node last = head; while(last.next != null){ last = last.next; } next = curr.next; last.next = next; curr.next = next.next; }
这里有两个关键错误:
- 未断开原尾节点的前连接:你找到了尾节点
last,但没记录它的前一个节点。原来的倒数第二个节点还指向last,这会导致链表形成环(比如原链表1->2->3->4->5,执行后会出现4->5->2->3->4的循环)。 - 错误修改首节点的后继:你把
curr.next直接设为next.next(原第三个节点),跳过了第二个节点,完全偏离了需求逻辑。
另外,你的main方法里还有个类型不匹配的问题:前面添加的都是整数,最后却加了字符串"Ginger",如果你的Node类存储的是整数类型,这会直接导致编译或运行报错。
修正后的Manipulate方法
正确的操作逻辑应该是:
- 找到尾节点
last,同时记录它的前一个节点prevLast - 把
last从原链表断开(让prevLast.next = null) - 将
last的后继指向原首节点的下一个节点 - 把原首节点的后继改为
last
修正后的代码:
public void Manipulate() { // 空链表或只有一个节点时无需操作 if (head == null || head.next == null) { return; } Node prevLast = null; Node last = head; // 遍历找到尾节点和它的前一个节点 while (last.next != null) { prevLast = last; last = last.next; } // 断开原尾节点的连接 prevLast.next = null; // 把尾节点接到首节点的下一个位置 last.next = head.next; head.next = last; }
修正main方法的类型问题
去掉添加字符串的代码,保持链表元素类型统一:
public static void main(String[] args) { Scanner sc = new Scanner(System.in); SinglyLinkedList lista = new SinglyLinkedList(); int a = sc.nextInt(); int b = sc.nextInt(); lista.addFirst(a); lista.insertAfter(a, b); for(int i = 0; i < 2; i ++){ int c = b; b = sc.nextInt(); lista.insertAfter(c, b); } lista.addLast(34); lista.addLast(55); // 移除类型不匹配的代码:lista.addLast("Ginger"); lista.Manipulate(); System.out.println(lista); }
测试验证
假设你输入的整数构建出类似1->2->3->4->5的链表,执行修正后的代码后,链表就会变成1->5->2->3->4,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Anthino Russo
相关产品推荐
相关产品推荐

