Java链表末尾插入节点问题:购物单程序输出顺序错误求助
链表末尾插入元素的错误修正方案
问题背景
实验要求基于不可修改的ShoppingList类main()方法,在ItemNode类中实现insertAtEnd()方法,完成向链表末尾添加元素的功能,且最终输出需跳过哑头节点,按输入顺序打印物品。
示例输入:
4 Kale Lettuce Carrots Peanuts
预期输出(按输入顺序):
Kale Lettuce Carrots Peanuts
错误原因分析
你实现的insertAtEnd()采用了头插法逻辑:每次将新节点插入到哑头节点的直接后继位置,导致新元素始终出现在链表最前端,最终输出顺序与输入完全相反。
修正后的ItemNode类代码
public class ItemNode { private String item; private ItemNode nextNodeRef; // Reference to the next node public ItemNode() { item = ""; nextNodeRef = null; } // Constructor public ItemNode(String itemInit) { this.item = itemInit; this.nextNodeRef = null; } // Constructor public ItemNode(String itemInit, ItemNode nextLoc) { this.item = itemInit; this.nextNodeRef = nextLoc; } // Insert node after this node. public void insertAfter(ItemNode nodeLoc) { ItemNode tmpNext; tmpNext = this.nextNodeRef; this.nextNodeRef = nodeLoc; nodeLoc.nextNodeRef = tmpNext; } // 正确实现的insertAtEnd()方法 public void insertAtEnd(ItemNode headNode, ItemNode currNode){ // 利用当前lastNode(this)是链表末尾节点的特性,直接将其next指向新节点 this.nextNodeRef = currNode; // 新节点的next已经在构造器中设为null,无需额外修改 } // Get location pointed by nextNodeRef public ItemNode getNext() { return this.nextNodeRef; } public void printNodeData() { System.out.println(this.item); } }
逻辑说明
结合ShoppingList的main()方法逻辑:
- 每次循环中,
lastNode始终指向当前链表的最后一个节点 - 调用
lastNode.insertAtEnd()时,this就是lastNode,只需将this.nextNodeRef指向新创建的currNode,就能完成末尾插入 - 新节点的
nextNodeRef在构造器中已初始化为null,无需额外处理,保证链表末尾节点的next为null
这样修改后,新元素会依次追加到链表末尾,最终输出顺序与输入完全一致。
内容的提问来源于stack exchange,提问作者Jeska Call
相关产品推荐
相关产品推荐

