题目描述
给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例1:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
进阶:思考一下,假设这些数位是正向存放的,又该如何解决呢?
示例2:
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912
解题思路
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
flag=False
a=l1
while l2:
if flag:
l1.val = l1.val+l2.val+1
flag = False
else:
l1.val += l2.val
if l1.val > 9:
flag=True
l1.val = l1.val % 10
if l2.next is not None and l1.next is None: ##L2比L1长,则在L1后面插入0
l1.next = ListNode(0)
elif l1.next is None and flag:
flag = False
l1.next = ListNode(1)
l1 = l1.next
l2 = l2.next
while l1:
if flag:
l1.val += 1
flag=False
if l1.val>9 and l1.next is not None:
l1.val %= 10
flag = True
elif l1.val>9 and l1.next is None:
l1.val %= 10
l1.next = ListNode(1)
break
l1 = l1.next
return a
标签:面试题,val,02.05,None,next,链表,flag,l2,l1
From: https://www.cnblogs.com/cleveresthuang/p/16929535.html