LeetCode 2. Add Two Numbers

Problem Statement

The problem is as follows: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.

Steps to Solve/ Approach

  • We create a dummy node to serve as the starting point of our result linked list. This dummy node will help simplify the code.

  • We initialize two variables: cur (the current node) and carry. The cur variable helps us build the result linked list, and carry stores the carry-over from the previous addition (initially set to 0).

  • We use a while loop that continues until both linked lists have been processed and there is no remaining carry.

  • Within the loop, we extract the values from the current nodes of both linked lists (if available) and add them together, along with the carry.

  • We calculate the new value to insert in the result linked list and update the carry based on the division result of the sum by 10.

  • We create a new node with the calculated value and append it to the result linked list, updating the cur pointer.

  • We move to the next nodes in both linked lists (if available) for the next iteration.

  • Finally, we return the result linked list starting from the node after the dummy node.

Code

# 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]:
        dummy = ListNode()
        cur = dummy

        carry = 0
        while l1 or l2 or carry:
            v1 = l1.val if l1 else 0
            v2 = l2.val if l2 else 0

            # New digit
            val = v1 + v2 + carry
            carry = val // 10
            val = val % 10
            cur.next = ListNode(val)

            # Updating
            cur = cur.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next