替换 LinkedList 中的节点实际上并没有替换任何东西

Replacing Node in LinkedList not actually replacing anything

我目前正在编写双向链表的实现,但无法将节点设置为特定值。由于节点中的数据是最终的,我需要替换整个节点,但我为此编写的代码似乎一直有效,直到它退出该方法并且原始列表根本没有改变。此处的代码中是否缺少任何内容?

`public void set(int index, String item) {
            if (index < 0 || index >= this.size) {
                throw new IndexOutOfBoundsException();
            }
            Node curr = this.front;
            for (int i = 0; i < index; i++) {
                curr = curr.next;
            }
            Node temp = new Node(item);
            temp.prev = curr.prev;
            temp.next = curr.next;
            curr = temp;
        }`

您还应该更改“上一个节点的next”和“下一个节点的prev”。假设prevcur的前一个节点,nextcur的下一个节点。

Node temp = new Node(item);
temp.prev = prev;
temp.next = next;
next.prev = temp;
prev.next = temp;

你应该处理边缘问题。

你可以

 System.out.println(curr.val);

你发现印刷品实际上与商品相同

但是当你 return 时,你会发现没有任何变化

你只需要找到curr的前节点并设置pre.next= curr(where is changed)

`public void set(int index, String item) {
        if (index < 0 || index >= this.size) {
            throw new IndexOutOfBoundsException();
        }
        Node curr = this.front;
        for (int i = 0; i < index; i++) {
            curr = curr.next;
        }
        Node temp = new Node(item);
        temp.prev = curr.prev;
        temp.next = curr.next;
        curr = temp;
        //here you need to set maybe 
         // Node tmp=curr.prev;
         // tmp.next=curr;
    }`