Skip to content

Instantly share code, notes, and snippets.

@hongtaoh
Created October 10, 2024 00:25
Show Gist options
  • Save hongtaoh/4436c3a8cc18b74a51d9fdc5188b1b91 to your computer and use it in GitHub Desktop.
Save hongtaoh/4436c3a8cc18b74a51d9fdc5188b1b91 to your computer and use it in GitHub Desktop.
Solution to Leetcode 23 Merge k Sorted Lists
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
# credit: https://www.youtube.com/watch?v=q5a5OiGbT6Q
if not lists or len(lists) == 0:
return None
while len(lists) > 1:
res = []
for i in range(0, len(lists), 2):
list1 = lists[i]
list2 = lists[i+1] if i < len(lists) - 1 else None
res.append(self.mergeTwoLists(list1, list2))
lists = res
return lists[0]
def mergeTwoLists(self, list1, list2):
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