-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adds two objects in reverse sorted singly linked lists together
- Loading branch information
1 parent
a8dcdf8
commit acd241e
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |