0712 更新
# 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:
index = 1
jinwei = 0
newhead = None
while l1 != None or l2 != None:
l1val = l1.val if l1 != None else 0
l2val = l2.val if l2 != None else 0
thisres = l1val + l2val + jinwei#index*(l1.val + l2.val + jinwei)
if thisres <= 9:
jinwei = 0
real_thisres = thisres
else:
jinwei = 1
real_thisres = thisres - 10
if newhead == None:
newhead = ListNode(real_thisres)
cur = newhead
else:
cur.next = ListNode(real_thisres)
cur = cur.next
l1 = l1.next if l1 != None else None
l2 = l2.next if l2 != None else None
if l1 == None and l2 == None:
if jinwei > 0:
cur.next = ListNode(jinwei)
return newhead
我实现了两种方法
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:
stra = ''
strb = ''
while l1 is not None:
stra = str(l1.val) + stra
l1 = l1.next
while l2 is not None:
strb = str(l2.val) + strb
l2 = l2.next
res = str(int(stra) + int(strb))
res = res[::-1]
length = len(res)
rootnode = ListNode(int(res[0]))
if length == 1:
return rootnode
for i in range(length):
if i == 0:
tempnode = rootnode
else:
tempnode.next = ListNode(int(res[i]))
tempnode = tempnode.next
return rootnode
2、逐位相加法
# 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:
temp = 0
toreturn = []#存放结果中的每一位数字
while l1 is not None and l2 is not None:
temp_res = l1.val + l2.val + temp
temp = 0
if temp_res >= 10:
temp_res -= 10
temp = 1
toreturn.append(temp_res)
l1 = l1.next
l2 = l2.next
if l1 is None and l2 is not None:
while l2 is not None:
temp_res = l2.val+temp
if temp_res >= 10:
toreturn.append(temp_res-10)
temp = 1
else:
toreturn.append(temp_res)
temp = 0
l2 = l2.next
if temp == 1:
toreturn.append(1)
return self.list2listnode(toreturn)
if l2 is None and l1 is not None:
while l1 is not None:
temp_res = l1.val + temp
if temp_res >= 10:
toreturn.append(temp_res-10)
temp = 1
else:
toreturn.append(temp_res)
temp = 0
l1 = l1.next
if temp == 1:
toreturn.append(1)
return self.list2listnode(toreturn)
if l1 is None and l2 is None:
if temp == 1:
toreturn.append(temp)
return self.list2listnode(toreturn)
def list2listnode(self,input_list):
length = len(input_list)
if length == 1:
return ListNode(input_list[0])
for i in range(length-1):
if i == 0:
rootnode = ListNode(input_list[0])
tempnode = ListNode(input_list[1])
rootnode.next = tempnode
else:
tempnode.next = ListNode(input_list[i+1])
tempnode = tempnode.next
return rootnode