-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path23_merge_k_sorted_list.py
50 lines (40 loc) · 1.2 KB
/
23_merge_k_sorted_list.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
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:param lists: List[ListNode]
:return: ListNode
"""
nums = []
for list_node in lists:
current = list_node
while current:
nums.append(current.val)
current = current.next
nums.sort()
head = ListNode(0)
tail = head
for num in nums:
tail.next = ListNode(num)
tail = tail.next
return head.next
list1 = ListNode(1)
list1.next = ListNode(4)
list1.next.next = ListNode(5)
list2 = ListNode(1)
list2.next = ListNode(3)
list2.next.next = ListNode(4)
list3 = ListNode(2)
list3.next = ListNode(6)
head_node = Solution().mergeKLists([list1, list2, list3])
assert head_node.val == 1
assert head_node.next.val == 1
assert head_node.next.next.val == 2
assert head_node.next.next.next.val == 3
assert head_node.next.next.next.next.val == 4
assert head_node.next.next.next.next.next.val == 4
assert head_node.next.next.next.next.next.next.val == 5
assert head_node.next.next.next.next.next.next.next.val == 6