Skip to content

Instantly share code, notes, and snippets.

@igorLisovitskiy
Created August 31, 2021 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorLisovitskiy/0d3121328d4a417dbe026aa993781f6a to your computer and use it in GitHub Desktop.
Save igorLisovitskiy/0d3121328d4a417dbe026aa993781f6a to your computer and use it in GitHub Desktop.
# 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]:
return self.add_nodes(l1, l2)
def add_nodes(self, l1, l2, prev_node=None, carried_over=0):
total_sum = carried_over
to_carry_over = 0
next_node_1, next_node_2 = None, None
if l1 or l2:
if l1:
total_sum += l1.val
next_node_1 = l1.next
if l2:
total_sum += l2.val
next_node_2 = l2.next
if total_sum > 9:
total_sum = total_sum - 10
to_carry_over = 1
if not prev_node:
node = ListNode(val=total_sum, next=None)
else:
node = ListNode(val=total_sum, next=None)
prev_node.next = node
self.add_nodes(next_node_1, next_node_2, node, to_carry_over)
return node
else:
if carried_over > 0:
prev_node.next = ListNode(val=carried_over, next=None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment