Problem
Solution
We can easily see that this problem is just elementary school math, except that the digits are divided into nodes in the linked lists.
Turn each list into an integer, then add the two numbers up.
Finally, turn the sum into a linked list by iterating through the digits.
Time Complexity
O(N1+N2), where N1 and N2 are the numbers of elements in each input list.
Space Complexity
O(1)
# 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
"""
if not l1 and not l2:
return None
l1_num = l2_num = 0
while l1:
l1_num = l1_num * 10 + l1.val
l1 = l1.next
while l2:
l2_num = l2_num * 10 + l2.val
l2 = l2.next
root = curr = ListNode(0)
for n in str(l1_num + l2_num):
curr.next = ListNode(int(n))
curr = curr.next
return root.next
'CODE > Algorithms & Data Structures' 카테고리의 다른 글
[LeetCode] Copy List with Random Pointer (0) | 2021.10.20 |
---|---|
[LeetCode] Merge k Sorted Lists (0) | 2021.10.18 |
[LeetCode] Linked List Cycle (0) | 2021.10.17 |
[LeetCode] Add Two Numbers (0) | 2021.10.17 |
[LeetCode] Trapping Rain Water (0) | 2021.10.15 |