【leetcode系列】【py3】【中等】两数相加
题目:
原题链接: https://leetcode-cn.com/problems/add-two-numbers/
解题思路:
虽然是个中等难度的,但是其实没太想明白难点在哪里
同时遍历两个链表,记录下是否需要进位,然后继续遍历就好了
代码实现:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = l1
is_add = 0
while l1 and l2:
l1.val += l2.val + is_add
if l1.val >= 10:
l1.val -= 10
is_add = 1
else:
is_add = 0
if not l1.next and not l2.next:
break
elif not l1.next:
l1.next = ListNode(0)
elif not l2.next:
l2.next = ListNode(0)
l1 = l1.next
l2 = l2.next
if is_add == 1:
l1.next = ListNode(1)
return head