【发布时间】:2017-06-13 17:37:42
【问题描述】:
我正在尝试将数字转换为链表(例如 617 到 7->1->6)
这是我的代码:
# 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
我对这部分进行了编码,并且这段代码有效。我只是不明白为什么“sum_head”能够链接到第二个节点“sum_node”。
以下是 Python 中的示例:
a = <Object>
b = a
b 只是对 a 的引用,这样对吗?
说将 617 转换为 7->1->6。按照我的代码,头部是 7,链表的其余部分是 7->1->6。头部怎么知道下一个节点是1?
【问题讨论】:
-
不,
b不是对a的引用。它们都是同一个对象的名称。
标签: python algorithm linked-list