[LeetCode] 2. Addition of Two Numbers

Title Description
_gives two non-empty linked lists to represent two non-negative integers. Among them, their respective locations are stored in reverse order, and each of their nodes can only store one digit.
If we add the two numbers together, we return a new linked list to represent their sum.
For example, input (2->4->3)+ (5->6->4)
Output: 7 - > 0 - > 8
Because 342 + 465 = 807
Main idea
_pointer p and q are traversal pointers of linked list L 1 and l2 respectively. If the number of Vals at p and q positions is greater than or equal to 10, then carry mark addflag=1. If addflag=1, it will enter 1 at the next node.
Code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l3 = None
        # Used to return the established new linked list
        l3_ini = None 
        
        p, q = l1, l2
        self.addflag = 0
        while p and q:
            num = p.val + q.val
            newNode = ListNode(num%10)
            # If the position is to be carried
            if self.addflag == 1:
                newNode.val += 1
                self.addflag = 0
                # Here we check if we need to carry again after carry-in.
                if newNode.val >= 10:
                    newNode.val = newNode.val % 10
                    self.addflag = 1
            if l3 == None:
                l3 = newNode
                l3_ini = newNode
            else:
                l3.next = newNode
                l3 = newNode
            if num >= 10:
                self.addflag = 1
            p = p.next
            q = q.next
        # When the length of two numbers is inconsistent, add the remainder to the list
        while p:
            newNode = p
            if self.addflag == 1:
                newNode.val += 1
                self.addflag = 0
                if newNode.val >= 10:
                    newNode.val = newNode.val % 10
                    self.addflag = 1
            l3.next = newNode
            l3 = newNode
            p = p.next
        while q:
            newNode = q
            if self.addflag == 1:
                newNode.val += 1
                self.addflag = 0
                if newNode.val >= 10:
                    newNode.val = newNode.val % 10
                    self.addflag = 1
            l3.next = newNode
            l3 = newNode
            q = q.next
        # Solve the problem of two digits plus two digits equaling three digits, for example.
        if self.addflag == 1:
            newNode = ListNode(1)
            l3.next = newNode
            l3 = newNode
            self.addflag = 0
        return l3_ini        
            

Posted on Fri, 11 Oct 2019 10:47:02 -0700 by boogybren