forked from AishwaryaBarai/Leetcode-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path148. Sort List
40 lines (38 loc) · 1.15 KB
/
148. Sort List
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
temp = head
slow = head
fast = head
while fast != None and fast.next != None:
temp = slow
slow = slow.next
fast = fast.next.next
temp.next = None
left_side = self.sortList(head)
right_side = self.sortList(slow)
return self.mergeList(left_side, right_side)
def mergeList(self,l1,l2):
sorted_temp = ListNode(0)
curr = sorted_temp
while l1 != None and l2 != None:
if(l1.val < l2.val):
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1 != None:
curr.next = l1
l1 = l1.next
if l2 != None:
curr.next = l2
l2 = l2.next
return sorted_temp.next