-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0148-sort-list.py
42 lines (32 loc) · 932 Bytes
/
0148-sort-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
# Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
array = []
while head:
array.append(head.val)
head = head.next
array.sort()
if not array:
return
root = ListNode(array[0])
current = root
for i in range(1,len(array)):
current.next = ListNode(array[i])
current = current.next
return root
def printLinkedList(head):
current = head
while current:
print(current.val, end=" -> ")
current = current.next
print("None")
root = ListNode(4)
root.next = ListNode(2)
root.next.next = ListNode(1)
root.next.next.next = ListNode(3)
printLinkedList(Solution().sortList(root))