[英]Linked list setting up reference
有人可以解释为什么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
}
您希望在index
位置的节点之前插入新节点(由temp
变量引用current.getNext()
,在while循环完成后由current.getNext()
引用。
因此,首先将下一个temp
of temp
为current.getNext()
( temp.setNext(current.getNext());
)然后将下一个current
节点设置为temp
( current.setNext(temp);
)。 这会在current
和原始current.getNext()
之间放置temp
。
之前:
... -> current -> current.getNext() -> ...
之后:
... -> current -> temp -> current.getNext() (the original current.getNext()) -> ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.