原题
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例
给出两个链表 3->1->5->null和5->9->2->null,返回 8->0->8->null
解题思路
- 简单的链表操作,注意声明一个carry来记录进位的结果
- 最后要记得check如果carry == 1的情况,否则9->9 + 1 = 0->0
完整代码
# 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
"""
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 Dummy.next