Created
October 9, 2024 23:33
-
-
Save hongtaoh/cf758805eb3722c88f0eade9d978c423 to your computer and use it in GitHub Desktop.
Solution to Leetcode 21 Merge Two Sorted List
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 | |
class Solution: | |
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: | |
dummy = ListNode() | |
tail = dummy | |
while list1 and list2: | |
if list1.val < list2.val: | |
tail.next = list1 | |
list1 = list1.next | |
else: | |
tail.next = list2 | |
list2 = list2.next | |
tail = tail.next | |
if list1: | |
tail.next = list1 | |
elif list2: | |
tail.next = list2 | |
return dummy.next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment