Skip to content

Commit

Permalink
Create add-two-numbers.py
Browse files Browse the repository at this point in the history
Adds two objects in reverse sorted singly linked lists together
  • Loading branch information
gabedonnan authored Jan 12, 2023
1 parent a8dcdf8 commit acd241e
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions add-two-numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
lFinal = ListNode()
temp = lFinal
while l1 != None or l2 != None:
if l1 != None:
self.chainAdd(temp, l1.val)
l1 = l1.next
if l2 != None:
self.chainAdd(temp, l2.val)
l2 = l2.next
if temp.next == None and (l1 != None or l2 != None):
temp.next = ListNode()
temp = temp.next
return lFinal


def chainAdd(self, lis, num):
if lis.val + num > 9:
if lis.next != None:
lis.val = lis.val + num - 10
self.chainAdd(lis.next, 1)
else:
lis.val = lis.val + num - 10
lis.next = ListNode(val = 1)
else:
lis.val = lis.val + num

0 comments on commit acd241e

Please sign in to comment.