[LeetCode] 2, add two numbers. Difficulty Level: Moderate.


[LeetCode] 2, add two numbers. Difficulty Level: Moderate.

1. Topic

You are given two non-empty linked lists representing two non-negative integers. Each of their digits is stored in reverse order, and each node can only store one digit.

Please add two numbers and return a linked list representing the sum in the same form.

You can assume that neither number starts with a zero other than the number zero.

Example 1:

insert image description here
Example 2:

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

Example 3:

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

insert image description here

2. My answer

# 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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        head=ListNode(0,None)    
        tail=head
        quotient=0    # 初始化需要进位的商

        while l1 != None or l2 != None:
            # 将较短的链表用 0 填充
            if l1 == None:
                l1=ListNode(0,None)
            if l2 == None:
                l2=ListNode(0,None)
            
            mod = (l1.val+l2.val+quotient) % 10          # 余数
            quotient = (l1.val+l2.val+quotient) // 10    # 商
            tail.next = ListNode(mod,None)
            
            # 链表向后位移
            tail=tail.next
            l1=l1.next
            l2=l2.next
        
        # 判断求和链表是否需要扩充一位长度
        if quotient > 0:
            tail.next=ListNode(quotient,None)

        return head.next

Results of the:

执行用时:64 ms, 在所有 Python3 提交中击败了 39.91% 的用户
内存消耗:16.2 MB, 在所有 Python3 提交中击败了 5.12% 的用户

3. Knowledge points

1. The shorter linked list can be filled with 0, so that the two linked lists l1 and l2 can be traversed at the same time.

2. Skillfully use the "double pointer" combination of head node and tail node. This idea is very common in linked list problems. You can refer to [LeetCode] 203 to remove linked list elements. Difficulty Level: Easy. The introductory topic of linked list is worthy of in-depth study.

3. Quotient and remainder, and carry operations are commonly used in leetcode.

Guess you like

Origin blog.csdn.net/qq_43799400/article/details/130828380