# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
两种思路,要么扫两个链表,一位一位地加,要么直接将两个链表先转化为整数,然后再把和转成链表
"""
def ListNode2Int(l_in):#todo 这个函数对了
list_re=[]
while l_in!=None:
list_re.append(l_in.val)
l_in=l_in.next
int_q=0
for i in list_re[::-1]:
int_q=int_q*10+i
return int_q
sum_temp=ListNode2Int(l1)+ListNode2Int(l2)
list_sum_temp=[]
if sum_temp==0:
list_sum_temp.append(0)
else:
while sum_temp>0:
list_sum_temp.append(sum_temp%10)
sum_temp=sum_temp/10
l_head=ListNode()
l_r=l_head
for i in list_sum_temp:
l_head.next=ListNode(i)
l_head=l_head.next
return l_r.next
上边是第一种思路,分别将l1、l2转变成整数,所得的和转变成链表,下边是第二种思路将每一位l1、l2和上一位的进位相加,放入新的节点
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
第二种思路:只要l1、l2或者进位不全为零时,每一位相加,如果是大于10继续循环
"""
carrying_bit=0
l_head=ListNode()
l_r=l_head
while l1!=None or l2!=None or carrying_bit!=0:
if l1==None and l2==None:
sum_temp=carrying_bit
elif l1 == None:
sum_temp = l2.val + carrying_bit
elif l2 == None:
sum_temp = l1.val + carrying_bit
else:
sum_temp = l1.val +l2.val+ carrying_bit
if sum_temp>=10:
l_head.next=ListNode(sum_temp-10)
carrying_bit=1
else:
l_head.next=ListNode(sum_temp)
carrying_bit=0
if l1!=None:
l1=l1.next
else:
pass
if l2!=None:
l2=l2.next
else:
pass
l_head=l_head.next
return l_r.next
但是这种写法过于繁琐了,看看官方解题思路
class Solution:
def addTwoNumbers(self, l1, l2) :
val=carry_bit=0
l_r=l_head=ListNode()
while l1 or l2 or carry_bit:
val=carry_bit
if l1:val,l1=val+l1.val,l1.next
if l2:val,l2=val+l2.val,l2.next
carry_bit,val=divmod(val,10)
l_head.next=ListNode(val)
l_head=l_head.next
return l_r.next