2. Add Two Numbers
https://leetcode.com/problems/add-two-numbers
Python
Convert to list then calculate back
from typing import Optional, List
# 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]:
list1, list2 = [], []
while l1.next is not None:
list1.append(l1.val)
l1 = l1.next
list1.append(l1.val)
while l2.next is not None:
list2.append(l2.val)
l2 = l2.next
list2.append(l2.val)
result = list(str(
int(''.join([str(i) for i in list1[::-1]])) + \
int(''.join([str(i) for i in list2[::-1]]))
))
head = ListNode(val=result.pop(), next=None)
cur = head
while result:
cur.next = ListNode(val=result.pop(), next=None)
cur = cur.next
return head
One-pass Linked List travsal
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode()
cur = dummy_head
cur1, cur2 = l1, l2
carry = 0
while cur1 or cur2:
if not cur1:
value = cur2.val + carry
cur2 = cur2.next
elif not cur2:
value = cur1.val + carry
cur1 = cur1.next
else:
value = cur1.val + cur2.val + carry
cur1 = cur1.next
cur2 = cur2.next
cur.next = ListNode(val=value%10)
carry = value // 10
cur = cur.next
if carry:
cur.next = ListNode(val=carry)
return dummy_head.next