leetcode-2.两数相加

题目描述

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例 1:

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.

示例 2:

输入:l1 = [0], l2 = [0]
输出:[0]

示例 3:

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

思路

1. 循环的条件:l1,l2,进位,至少还有一个有值,就循环下去

2. 链表节点的值由3部分组成:l1.val+l2.val+进位

    2.1 节点的值:3个数的和 % 10

    2.2 进位:3个数的和 // 10 

3. l1,l2,头节点各自next

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = pre = ListNode(-1)
        val = carry = 0
        while l1 or l2 or carry > 0:
            val = carry
            if l1:
                val += l1.val
                l1 = l1.next
            if l2:
                val += l2.val
                l2 = l2.next
            carry = val // 10
            head.next = ListNode(val % 10)
            head = head.next
        return pre.next


if __name__=='__main__':
    s=Solution()
    head1=ListNode(9)
    phead1=head1
    data1=[9,9,9,9,9,9]
    for i in data1:
        node=ListNode(i)
        phead1.next=node
        phead1=phead1.next

    head2 = ListNode(9)
    phead2 = head2
    data2 = [9,9,9]
    for i in data2:
        node = ListNode(i)
        phead2.next = node
        phead2 = phead2.next
    head = s.addTwoNumbers(head1,head2)
    while head:
        print(head.val)
        head=head.next

你可能感兴趣的:(leetcode,hot100,leetcode,算法)