Java Reference
In-Depth Information
that you want to insert the value 5 at index 2. You'd want to position the variable
current to point at the value with index 1 (the node storing 8 ):
data
19
next
data
8
next
data
42
next
/
front
current
Now you can change the value of current.next to add the new node. This new
node should have a data value of 5 . To what should its next link refer? It should refer
to the node that has 42 in it, which is stored in current.next . So you'll want to
construct the node as follows:
new ListNode(5, current.next)
Just calling the constructor leaves the computer's memory looking like this:
data
5
next
data
19
next
data
8
next
data
42
next
/
front
current
Your code is not complete. You've constructed a node that points at the list, but
nothing in the list points at the node. Thus, you've taken care of half of what you
need to do. The other half of the task is to change a link of the list to point to the new
node. The link to change is current.next :
current.next = new ListNode(5, current.next);
After this modification has been made, the list will look like this:
next
data
5
next
next
next
/
data
19
data
8
data
42
front
current
Search WWH ::




Custom Search