-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.merge-k-sorted-lists.py
51 lines (43 loc) · 1.14 KB
/
23.merge-k-sorted-lists.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#
# @lc app=leetcode id=23 lang=python3
#
# [23] Merge k Sorted Lists
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def SortedMerge(a, b):
result = ListNode()
tail = result
while True:
if a == None:
tail.next = b
break
if b == None:
tail.next = a
break
if a.val <= b.val:
tail.next = a
a = a.next
else:
tail.next = b
b = b.next
tail = tail.next
return result.next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if len(lists) == 0:
return None
finish = len(lists) -1
while finish > 0:
lists[0] = SortedMerge(lists[0], lists[finish])
finish -= 1
return lists[0]
# @lc code=end