自从工作了以后,已经很久没有看数据结构了,链表题也踌躇了好久,离谱
题意很简单,这种计算是小学就学过的,难点就在于怎么构建链表,上代码,第一遍不加思考暴力写的,链表只记得从后往前创建的,这样就需要有两个循环,先得到list,然后逆序创建链表,从前往后的忘了,写半天写出不来,太绕了。。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l3_list = []
val_1 = 0
while l1 or l2:
if l2 and l1 :
val = l1.val + l2.val + val_1
l1 = l1.next
l2 = l2.next
elif l2 :
val = l2.val + val_1
l2 = l2.next
else:
val = l1.val + val_1
l1 = l1.next
val, val_1 = self.cal(val)
l3_list.append(val)
if val_1 > 0:
l3_list.append(val_1)
l3 = ListNode(l3_list[-1], None)
for idx in range(1, len(l3_list)):
l3 = ListNode(l3_list[-idx - 1], l3)
return l3
def cal(self, val):
val_1 = 0
if val >= 10:
val_1 = 1
val = val - 10
return val, val_1
看了答案理解了一下,改写了一下,只需要一个循环就可搞定
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
val_1 = 0
head = l3_pre = ListNode()
while l1 or l2:
if l2 and l1 :
val = l1.val + l2.val + val_1
l1 = l1.next
l2 = l2.next
elif l2 :
val = l2.val + val_1
l2 = l2.next
else:
val = l1.val + val_1
l1 = l1.next
val, val_1 = self.cal(val)
l3_pre.next = ListNode(val)
l3_pre = l3_pre.next
if val_1 > 0:
l3_pre.next = ListNode(val_1)
return head.next
def cal(self, val):
val_1 = 0
if val >= 10:
val_1 = 1
val = val - 10
return val, val_1
把头定住,在循环中创建当前节点的写一个节点,然后将下一个节点赋值给当前节点,总结一下:
在循环中:
从前往后创建的话:a.next = ListNode(val)
a = a.next
从后往前创建的话:a = ListNode(val)
a.next = a