简体   繁体   中英

Linked list setting up reference

Can someone explain why temp.setNext(current.getNext()); has been used I am not understanding

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
        }

You want the new Node (referenced by the temp variable) to be inserted before the node at the index position, which is referenced by current.getNext() after the while loop is done.

Therefore you first set the next Node of temp to current.getNext() ( temp.setNext(current.getNext()); ) and then set the next Node of current to temp ( current.setNext(temp); ). This places temp between current and the original current.getNext() .

before :

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

after :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM