原題
假定用一個鏈表表示兩個數,其中每個節點僅包含一個數字。假設這兩個數的數字順序排列,請設計一種方法將兩個數相加,并將其結果表現為鏈表的形式。
樣例
給出 6->1->7 + 2->9->5。即,617 + 295。
返回 9->1->2。即,912 。
解題思路
- 整體思路與Add Two Numbers一樣,只不過鏈表和其表示的數值吮吸相同
- 借助helper函數,反轉鏈表
完整代碼
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists2(self, l1, l2):
# Write your code here
l1 = self.reverse(l1)
l2 = self.reverse(l2)
carry = 0
Dummy = ListNode(0)
head = Dummy
while l1 != None and l2 != None:
sum = (l1.val + l2.val + carry) % 10
carry = 1 if (l1.val + l2.val + carry) > 9 else 0
head.next = ListNode(sum)
head = head.next
l1 = l1.next
l2 = l2.next
while l1 != None:
sum = (l1.val + carry) % 10
carry = 1 if l1.val + carry > 9 else 0
head.next = ListNode(sum)
l1 = l1.next
head = head.next
while l2 != None:
sum = (l2.val + carry) % 10
carry = 1 if l2.val + carry > 9 else 0
head.next = ListNode(sum)
l2 = l2.next
head = head.next
if carry:
head.next = ListNode(carry)
return self.reverse(Dummy.next)
def reverse(self, head):
if not head:
return head
prev = None
while head != None:
temp = head.next
head.next = prev
prev = head
head = temp
return prev