I was practicing some algorithms, and I once saw this code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
q = 0
head = new_LN = ListNode(0)
while l1 or l2:
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
q, r = divmod(q l1_val l2_val , 10)
new_LN.next = ListNode(r)
new_LN = new_LN.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
if q:
new_LN.next = ListNode(q)
return head.next
# print(new_LN) # ListNode{val: 8, next: None}
# print(head) # ListNode{val: 0, next: ListNode{val: 7, next: ListNode{val: 0, next: ListNode{val: 8, next: None}}}}
In an example, the results of new_LN and head are stated above.
I cannot understand why head and new_LN are different though they were declared on the same line.
Can anybody explain this one for me?
CodePudding user response:
what you need to understand is that both head
and new_LN
are pointers to an object and not the object itself, so at the beginning of the code when the line head = new_LN = ListNode(0)
is called a new ListNode object is created and both head
and new_LN
are pointing to it.
but when the line new_LN = new_LN.next
is called, the pointer new_LN
is set to point to another object while head
still points to the original node,
so that's why at the end of the code head
and new_LN
are not equal
hope I could clarify that for you if you have any questions feel free to ask me in the comments, and if my comment helped you marking it as the answer or upvoting will go a long way :)