gpt4 book ai didi

java - 链表设置引用

转载 作者:太空宇宙 更新时间:2023-11-04 12:39:01 26 4
gpt4 key购买 nike

谁能解释一下为什么temp.setNext(current.getNext());已经用过,不太明白

public void add(Object data, int index)
// post: inserts the specified element at the specified position in this list.
{
Node temp = new Node(data);
Node current = head;
// crawl to the requested index or the last element in the list,
// whichever comes first
for(int i = 1; i < index && current.getNext() != null; i++)
{
current = current.getNext();
}
// set the new node's next-node reference to this node's next-node reference
temp.setNext(current.getNext());
// now set this node's next-node reference to the new node
current.setNext(temp);
listCount++;// increment the number of elements variable
}

最佳答案

您希望将新节点(由 temp 变量引用)插入到 index 位置处的节点之前,该位置在 while 循环完成后由 current.getNext() 引用。

因此,首先将 temp 的下一个节点设置为 current.getNext() (temp.setNext(current.getNext());),然后将 current 的下一个节点设置为 temp (current.setNext(temp);)。这会将 temp 置于 current 和原始 current.getNext() 之间。

之前:

... -> current -> current.getNext() -> ...

之后:

... -> current -> temp -> current.getNext() (the original current.getNext()) -> ...

关于java - 链表设置引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37019117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com