解法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:
n1 = 0
n2 = 0
def make_list_node(in_list):
now_list_node = ListNode(in_list[0])
head = now_list_node
if len(in_list) == 1:
return now_list_node
for i in range(1,len(in_list)):
list_node = ListNode(in_list[i])
now_list_node.next = list_node
now_list_node = list_node
return head
while l1:
n1 *= 10
n1 += l1.val
l1 = l1.next
if not l1:
break
while l2:
n2 *=10
n2 += l2.val
l2 = l2.next
if not l2:
break
n = n1 + n2
return make_list_node( list(map(int, list(str(n)))) )
解法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:
n1 = []
n2 = []
while l1:
n1.append(l1.val)
l1 = l1.next
if not l1:
break
while l2:
n2.append(l2.val)
l2 = l2.next
if not l2:
break
now_list_node = None
in_flag = 0
if min(len(n1),len(n2)) >= 1:
t1 = n1.pop()
t2 = n2.pop()
print(t1,t2)
t = t1+t2+in_flag
in_flag = 0
if t>=10:
t = t-10
in_flag = 1
now_list_node = ListNode(t)
for i in range(0,max(len(n1),len(n2))):
t1 = n1.pop() if n1 else 0
t2 = n2.pop() if n2 else 0
print(t1,t2)
t = t1+t2+in_flag
in_flag = 0
if t>=10:
t = t-10
in_flag = 1
# print(t0)
new_list_node = ListNode(t)
new_list_node.next = now_list_node
now_list_node = new_list_node
if len(n1)==0 and len(n2) == 0 and in_flag == 1:
new_list_node = ListNode(in_flag)
new_list_node.next = now_list_node
now_list_node = new_list_node
return now_list_node
Post Views: 861
留言