LeetCode-两数相加

LeetCode 2. 两数相加

题目难度:中等
LeetCode-两数相加_第1张图片
题目分析:

  • 链表反向存储数据,也就是第一位是个位;
  • 1、l1为空或l2为空,返回另一个链表即可;
  • 2、做加法运算时需要考虑进位,创建变量carry保存进位;
  • 3、对链表进行遍历,直到其中一个链表遍历完全;
  • 4、遍历结束,考虑进位;
    —直接和不为空的链表的后一项相加;
    —两个链表都遍历完成,则需要将进位添加到后面;
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        
        carry = 0
        dummy = ListNode(0)
        p = dummy

        while l1 and l2:
            p.next = ListNode((l1.val + l2.val + carry) % 10)
            carry = (l1.val + l2.val + carry)//10
            l1 = l1.next
            l2 = l2.next
            p = p.next
        if l2:
            while l2:
                p.next = ListNode((l2.val + carry) % 10)
                carry = (l2.val + carry)//10
                l2 = l2.next
                p = p.next
        if l1:
            while l1:
                p.next = ListNode((l1.val + carry) % 10)
                carry = (l1.val + carry)//10
                l1 = l1.next
                p = p.next    
        if carry == 1:
            p.next = ListNode(1)

        return dummy.next

测试通过。
LeetCode-两数相加_第2张图片

你可能感兴趣的:(LeetCode刷题-,python篇,leetcode,链表,算法)