原题链接:https://leetcode.com/problems/add-two-numbers/
我的思路:
这道题其实可以分为一下几个步骤(iterative):
- 把输入的链表的值复制下来,存到一个列表中
- 把列表倒置过来得到对应数字,比直接倒置链表要快很多
- 将这两个值加在一起,得到题目中要求的two numbers sum
- 把得到的两数之和倒转,变成链表返回
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
l1_val = self.node_val(l1)
l2_val = self.node_val(l2)
l1_int = self.get_int(l1_val)
l2_int = self.get_int(l2_val)
sum_int = l1_int + l2_int
sum_str = str(sum_int)
sum_lst = []
for i in sum_str:
sum_lst.append(i)
sum_lst = sum_lst[::-1]
sum_ll = self.LinkedList(sum_lst)
return sum_ll
def node_val(self, linkedlist):
node_val = []
while linkedlist:
node_val.append(linkedlist.val)
linkedlist = linkedlist.next
node_val = node_val[::-1]
return node_val
def get_int(self, lst):
sum_val = 0
for i in range(len(lst)):
itg = lst[i] * (10**(len(lst)-1-i))
sum_val += itg
return sum_val
def LinkedList(self, lst):
cur = dummy = ListNode(0)
for e in lst:
cur.next = ListNode(e)
cur = cur.next
return dummy.next
讨论里看到的做法:(recursive)比遍历的做法稍微快一些
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode(0)
result_tail = result
carry = 0
while l1 or l2 or carry:
val1 = (l1.val if l1 else 0)
val2 = (l2.val if l2 else 0)
carry, out = divmod(val1+val2 + carry, 10)
result_tail.next = ListNode(out)
result_tail = result_tail.next
l1 = (l1.next if l1 else None)
l2 = (l2.next if l2 else None)
return result.next
另外一个遍历的做法,与我的思路相同,但是代码写得更为简洁一些:
class Solution:
def to_int(l: ListNode):
s = ''
while l != None:
s += str(l.val)
l = l.next
return int(s[::-1])
def to_list(n: int):
s = str(n)[::-1]
head = prev = None
for ch in s:
node = ListNode(int(ch))
if prev is not None:
prev.next = node
prev = node
if head is None:
head = prev
return head
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a = Solution.to_int(l1)
b = Solution.to_int(l2)
return Solution.to_list(a + b)