LeetCode #2 – Add Two Numbers [链表操作]

Leetcode题目链接

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

题意:给定两个倒序链表形式的两个大数,返回链表形式的两数之和。

题目中的样例相当于342 + 465 = 807.链表操作时,因为是倒序的,从前往后依次相加,满十进位即可。注意返回时要返回首节点,不要弄错。

 

class Solution:
    def addTwoNumbers(self, l1, l2):
        res, sum = ListNode(0), 0
        ret = res
        while True:
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            sum, res.val = sum // 10, sum % 10
            if sum or l1 or l2:
                res.next = ListNode(0)
                res = res.next
            else: break
        return ret

欢迎留言