LeetCode 445 - Add Two Numbers II Problem

Problem Statement

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

Solution:

# 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: s1 = [] s2 = [] #push all elements onto stack while l1!=None: s1.append(l1.val) l1 = l1.next while l2!=None: s2.append(l2.val) l2 = l2.next #create dummy node dummy = ListNode(0) l3 = dummy carry=0 while len(s1)>0 or len(s2)>0: l1_value = l2_value = 0 if len(s1)>0: l1_value = s1.pop() if len(s2)>0: l2_value = s2.pop() #do addition curr_sum = l1_value + l2_value + carry carry = curr_sum//10 last_digit = curr_sum%10 #add the new node to front of the linked list new_node = ListNode(last_digit) new_node.next = l3.next l3.next = new_node if carry>0: new_node = ListNode(carry) new_node.next = l3.next l3.next = new_node return dummy.next