Let head be pointing to the first element of the following linked list 1->2->3->Null
each element of the list is a Node() with attributes: val and next
when:
curr=head
head=head.next
curr.next.val= 1000
#here head.val outputs 1000 : We changed the value of the 2nd node
But when:
curr=head
head=head.next
curr.next= Node(1000)
#here head.val outputs 2, it seems that the change
#we made in the previous line didn't
#affect the node but rather created a new 'route'.
Could someone explain why in the first case we're modifying the node value w.r.t head and in the 2nd case we're not?
Thank you
Consider 3 nodes n1, n2, n3 in a linked list.
head = n1
curr = head
# All n1, head and curr will be pointing to same memory.
head = head.next
# head will be reasigned to n2, but curr points to n1 itself.
1st case
curr.next.val = 1000 # curr.next is same as n1.next which is n2 so n2.val becomes 1000 # As head points to n2 head.val is also 1000
2nd case
curr.next = node(1000) # it reassigns curr.next ie n1.next to new node with val = 1000 (head is unaltered) # Here as head points to n2, head.val = 2
head = head.next
reassigns only head
not curr
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.