自定义LinkedList类set方法无法修改元素问题求助
Fixing the
set() Method in Custom Generic LinkedList Hey there! Let's break down why your set() method isn't updating the linked list as expected, and how to fix it.
The Core Issue
The biggest problem is how you initialize your traversal node p. Right now, you're creating a brand new, disconnected Node<X> instead of starting from the actual head of your linked list (first). This means you're never actually touching the nodes in your existing list—you're modifying an empty, unrelated node instead.
Let's Walk Through the Original Code's Flaws
Node<X> p = new Node<X>();creates a node that has no connection to your linked list. Itsnextfield isnull, so your traversal loop can't reach any nodes in the list.- For index 0, the loop doesn't run at all, and you end up setting the item of this disconnected node (not the first node in your list).
- For indexes greater than 0, the loop would try to access
p.next(which isnull) and throw aNullPointerExceptionbefore even reaching the target node.
Corrected set() Method
Here's the fixed version that properly updates the intended node:
public void set(int index, X item) { // Validate the index first if (index < 0 || index > size() - 1) { throw new Bonfire(); // Keep your custom exception if that's intended } // Start traversal from the actual head of the list Node<X> p = first; int count = 0; // Traverse to the target index while (count != index) { p = p.next; count++; } // Update the item of the target node p.item = item; }
Why This Works
- By initializing
p = first, you start at the actual first node of your linked list, so your traversal moves through the real nodes in the list. - After looping
indextimes,ppoints directly to the node you want to modify. Assigningp.item = itemupdates the value of that node in the linked list, which your test will correctly pick up withget(0).
Since your add(), size(), and get() methods already work, this fix should make your test pass immediately.
内容的提问来源于stack exchange,提问作者Yoshi24517
相关产品推荐
相关产品推荐

