Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import itertools as it
class IterableListNode(ListNode):
@classmethod
def from_ListNode(cls, list_node):
return cls(list_node.val, list_node.next)
@classmethod
def from_iterable(cls, iterable):
head = None
node = cls()
for v in iterable:
node.next = cls()
node.next.val = v
node = node.next
if head is None:
head = node
return head
def __iter__(self):
self.current_node = self
return self
def __next__(self):
if self.current_node is None:
raise StopIteration
val = self.current_node.val
self.current_node = self.current_node.next
return val
def __add__(self, other):
def added_digits_iterator(l1, l2):
take_over = 0
for x, y in it.zip_longest(l1, l2, fillvalue=0):
xy = x + y + take_over
take_over = 1 if xy >= 10 else 0
yield xy % 10
if take_over == 1:
yield 1
return self.from_iterable(added_digits_iterator(self, other))
def adapt(*list_nodes):
return [IterableListNode.from_ListNode(ln) for ln in list_nodes]
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
it_l1, it_l2 = adapt(l1, l2)
return it_l1 + it_l2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment