链接列表设置参考

时间:2016-05-04 05:23:39

标签: java

有人可以解释原因 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
        }

1 个答案:

答案 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() -> ...