簡體   English   中英

鏈接列表設置參考

[英]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 tempcurrent.getNext()temp.setNext(current.getNext()); )然后將下一個current節點設置為tempcurrent.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM