解法:
初始化一個dummy_head,一個新的鏈表curr用於保存結果,逐位遍歷兩鏈表節點,將計算結果保存到curr鏈表中,直到兩鏈表節點均爲空。遍歷結束後carry非0,則將curr的next指向一個新的值爲carry的鏈表節點。
Python源碼:
# 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):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(0)
p = l1
q = l2
curr = dummy_head
carry = 0
while p or q:
if p:
x = p.val
else:
x = 0
if q:
y = q.val
else:
y = 0
digit = carry + x + y
carry = digit // 10
curr.next = ListNode(digit % 10)
curr = curr.next
if p:
p = p.next
if q:
q = q.next
if carry > 0:
curr.next = ListNode(carry)
return dummy_head.next
我的心路:
Runtime: 64 ms, faster than 22.34% of Python online submissions for Add Two Numbers.
Memory Usage: 12 MB, less than 13.97% of Python online submissions for Add Two Numbers.
# 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):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
c = False
res = l1
while l1 != None and l2 != None:
l1.val += l2.val
if c:
l1.val += 1
c = False
if l1.val >= 10:
l1.val %= 10
c = True
cur = l1
l1 = l1.next
l2 = l2.next
if l2 != None:
l1 = l2
cur.next = l1
while l1 != None:
if c:
l1.val += 1
c = False
if l1.val >= 10:
l1.val %= 10
c = True
cur = l1
l1 = l1.next
if c:
cur.next = ListNode(1)
return res
七個月前的解法,看起來比現在可讀性高一些,加入了dummy head,全面碾壓這次的解法:
Runtime: 60 ms, faster than 41.16% of Python online submissions for Add Two Numbers.
Memory Usage: 11.8 MB, less than 61.76% of Python online submissions for Add Two Numbers.
# 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):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = l = ListNode(0)
car = 0
while(l1 and l2):
l.next = ListNode((l1.val + l2.val + car) % 10)
car = (l1.val + l2.val + car) // 10
l1 = l1.next
l2 = l2.next
l = l.next
while(l1):
l.next = ListNode((l1.val + car) % 10)
car = (l1.val + car) // 10
l1 = l1.next
l = l.next
while(l2):
l.next = ListNode((l2.val + car) % 10)
car = (l2.val + car) // 10
l2 = l2.next
l = l.next
if(car):
l.next = ListNode(car)
return l3.next