有人可以解释原因 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
}
答案 0 :(得分:0)
您希望在temp
位置的节点之前插入新节点(由index
变量引用),该节点在while循环完成后由current.getNext()
引用。
因此,您首先将temp
的下一个节点设置为current.getNext()
(temp.setNext(current.getNext());
),然后将current
的下一个节点设置为temp
({{ 1}})。这会将current.setNext(temp);
放在temp
和原始current
之间。
之前:
current.getNext()
之后:
... -> current -> current.getNext() -> ...