原题
假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
样例
给出 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