【Daily Question】2. Add Two Numbers

Insert picture description here

The meaning of the question is that a number is stored in a linked list, with the head of the linked list in the low bit and the tail of the linked list in the high bit. Then the two numbers are added together and the new linked list is returned.

Algorithm idea: Traverse the two linked lists separately, add up each digit of the number, and you can get a new linked list. The idea is relatively simple, now I will focus on the details

  • Carry may occur: Carry is represented by a number carry, and the number at the current position after addition is (n1 + n2 + carry)% 10, and carry = (n1 + n2 + carry) // 10. When added to the highest bit, a carry may also occur. At this time, the value of the new node is carry
  • The length of the linked list is inconsistent: we can regard the value of the part of the node where the shorter linked list is shorter than the longer linked list as 0
  • The function of the pointer q in the code is that when p reaches the highest position, a next pointer that is not empty will be created. At this time, we need to use q to record the node before p, and set the next pointer at the highest position. Is empty
# 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:
        p = head = ListNode()  # p用来指示当前的结点
        carry = 0
        while(l1 or l2):
            n1 = l1.val if l1 else 0  #l1不为空那么数值就为l1.val如果为空就为0
            n2 = l2.val if l2 else 0
            p.val = (n1 + n2 + carry) % 10
            p.next = ListNode()
            q = p            # 用来记录p结点之前的结点,因为下一行中p变成了p.next
            p = p.next
            carry = (n1 + n2 + carry) // 10
            l1 = l1.next if l1 else l1
            l2 = l2.next if l2 else l2
        if(carry > 0):  			 #最高位还有进位
            p.val = carry
        else:
            q.next = None		#没有进位的话,把最高位的next指针置为空
        return head
        

The time complexity is: O(max(length of l1, length of l2))

Guess you like

Origin blog.csdn.net/SJTUKK/article/details/109155408