To add two numbers, traversal of Linked List will be done, both Linked List have to be of same length, inmaintaince_phase the loop should continue if one of the Linked List has element so use or condition in while loop to check if either of them is valid.
Code
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = nextdef addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode: carry = 0 dummy = ListNode() curr = dummy while l1 or l2 or carry: val1 = l1.val if l1 else 0 val2 = l2.val if l2 else 0 total = val1 + val2 + carry carry = total // 10 curr.next = ListNode(total % 10) curr = curr.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None return dummy.next# Example usagel1 = ListNode(2, ListNode(4, ListNode(3)))l2 = ListNode(5, ListNode(6, ListNode(4)))result = addTwoNumbers(l1, l2)# The result should be 7 -> 0 -> 8, which represents the number 807.