Created
July 11, 2025 14:08
-
-
Save tonussi/9e8624d8ca7dc33342ed9476e6487f59 to your computer and use it in GitHub Desktop.
Add two linked lists
This file contains hidden or 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
| # Definition for singly-linked list. | |
| # class ListNode: | |
| # def __init__(self, val=0, next=None): | |
| # self.val = val | |
| # self.next = next | |
| def build_list_nodes(arr: list, i: int) -> Optional[ListNode]: | |
| if i < 0: return None | |
| newNode = ListNode(arr[i]) | |
| newNode.next = build_list_nodes(arr, i - 1) | |
| return newNode | |
| class Solution: | |
| def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: | |
| current1 = l1 | |
| current2 = l2 | |
| n1 = str(current1.val) | |
| n2 = str(current2.val) | |
| while current1 is not None: | |
| current1 = current1.next | |
| if current1: n1 += str(current1.val) | |
| while current2 is not None: | |
| current2 = current2.next | |
| if current2: n2 += str(current2.val) | |
| n1 = n1[::-1] | |
| n2 = n2[::-1] | |
| n3 = int(n1)+int(n2) | |
| arr = [int(d) for d in str(n3)] | |
| narr = [] | |
| rl = build_list_nodes(arr, len(arr) - 1) | |
| return rl |
This file contains hidden or 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
| Input: l1 = [2,4,3], l2 = [5,6,4] | |
| Output: [7,0,8] | |
| Explanation: 342 + 465 = 807. | |
| Example 2: | |
| Input: l1 = [0], l2 = [0] | |
| Output: [0] | |
| Example 3: | |
| Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] | |
| Output: [8,9,9,9,0,0,0,1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment