You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义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. Its next field is null, 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 is null) and throw a NullPointerException before 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 index times, p points directly to the node you want to modify. Assigning p.item = item updates the value of that node in the linked list, which your test will correctly pick up with get(0).

Since your add(), size(), and get() methods already work, this fix should make your test pass immediately.

内容的提问来源于stack exchange,提问作者Yoshi24517

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:15:01