Skip to content

Commit 010e19f

Browse files
148. Sort List
Difficulty: 28 / 28 test cases passed. Runtime: 220 ms Memory Usage: 37.8 MB
1 parent 6886687 commit 010e19f

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Medium/148.SortList.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
Given the head of a linked list, return the list after sorting it in
3+
ascending order.
4+
5+
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory
6+
(i.e. constant space)?
7+
8+
Example:
9+
nput: head = [4,2,1,3]
10+
Output: [1,2,3,4]
11+
12+
Example:
13+
Input: head = [-1,5,3,4,0]
14+
Output: [-1,0,3,4,5]
15+
16+
Example:
17+
Input: head = []
18+
Output: []
19+
20+
Constraints:
21+
- The number of nodes in the list is in the range [0, 5 * 10**4].
22+
- -10**5 <= Node.val <= 10**5
23+
"""
24+
#Difficulty:
25+
#28 / 28 test cases passed.
26+
#Runtime: 220 ms
27+
#Memory Usage: 37.8 MB
28+
29+
#Runtime: 220 ms, faster than 66.14% of Python3 online submissions for Sort List.
30+
#Memory Usage: 37.8 MB, less than 6.25% of Python3 online submissions for Sort List.
31+
32+
# Definition for singly-linked list.
33+
# class ListNode:
34+
# def __init__(self, val=0, next=None):
35+
# self.val = val
36+
# self.next = next
37+
38+
class Solution:
39+
def sortList(self, head: ListNode) -> ListNode:
40+
if not head:
41+
return
42+
current = head
43+
values = []
44+
while current:
45+
values.append(current.val)
46+
current = current.next
47+
values.sort(reverse=True)
48+
head = ListNode(values.pop())
49+
node = head
50+
while values:
51+
node.next = ListNode(values.pop())
52+
node = node.next
53+
return head

0 commit comments

Comments
 (0)