I am trying to convert a number to a linked list (eg 617 to 7->1->6)
here is my code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
# write your code here
num_1 = num_2 = 0
counter = 1
# convert each linked list to an integer
while l1 != None:
num_1 += l1.val * counter
l1 = l1.next
counter *= 10
# reset counter
counter = 1
while l2 != None:
num_2 += l2.val * counter
l2 = l2.next
counter *= 10
# perform the addition
my_sum = num_1 + num_2
# convert the sum back to a linked list
# initialize head
sum_head = ListNode(my_sum % 10)
sum_node = sum_head
my_sum //= 10
while my_sum != 0:
sum_node.next = ListNode(my_sum % 10)
sum_node = sum_node.next
my_sum //= 10
# return the the linked list
return sum_head
I coded this part and this piece of code works. I just don't understand why the "sum_head" is able to link to the second node "sum_node".
Here is an example in Python:
a = <Object>
b = a
b is just a reference to a, is this correct?
Say convert 617 to 7->1->6. Followed my code, the head is 7 and the rest of the linked list is 7->1->6. How can the head knows that the next node is 1?
The first two variables aren't "linked" in the linked-list sense. They are the same object. This might be clearer if it is substituted for an equivalent expression:
sum_head = ListNode(my_sum % 10)
sum_node = sum_head
# ==
sum_node = sum_head = ListNode(my_sum % 10)
# So: sum_node.next is sum_head.next
Why do we need two variables pointing to to the same object? Because in the following lines, we change what the sum_node points to. It will become the .next
of the object it previously was. Since there is no way to go back, we need to keep a reference of the head to return it.
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.