编译语言:
python3
题目:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
(你会得到两个非空链表用来存储两个非负整数,数字以相反的顺序存储在每个节点中,把这两个数加起来,并以链表的形式返回)
example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
思路1:
刚开始的时候,我是想着每个节点的数相加之后,立即进行处理是否产生进位,然后得出最终的结果。代码如下:
代码解释:
temp1用来存储当前节点是否产生进位,并在下一个节点相加时进行判断。
特殊情况:
1.L1的长度大于L2的长度
2.L2的长度大于L1的长度
3.最后的结果比L1和L2的长度都要大
思路2:
上一个代码的效率并不是特别好,于是有了下面这个版本。这个版本和上一个版本的思路相反,即每个节点相加之后不进行进位处理,照相加的结果逐节点存放在链表中。最后遍历这个结果存放的节点,按结果是否大于10来处理,大于的话,则下一位+1,一直到最后一位。
代码:
# # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
h = l1
while True:
l1.val = l1.val + l2.val
if l1.next and l2.next:
l1, l2 = l1.next, l2.next
elif l2.next and not l1.next:
l1.next = l2.next
break
elif l1.next and not l2.next:
break
elif not l1.next and not l2.next:
break
l1 = h
while h:
if h.val>=10:
h.val = h.val -10
if h.next:
h.next.val = h.next.val + 1
elif not h.next:
h.next = ListNode(1)
h = h.next
return l1