CA 24 - Sort a Linked List using Merge Sort
Merge Sort for Linked List
You are given the head of a linked list. You have to sort the given linked list using Merge Sort.
Examples:
Input:

Output: 10 -> 20 -> 30 -> 40 -> 50 -> 60
Explanation: After sorting the given linked list, the resultant list will be:

Input:
Output: 2 -> 5 -> 8 -> 9
Explanation: After sorting the given linked list, the resultant list will be:
Constraints:
1 ≤ number of nodes ≤ 105
0 ≤ node->data ≤ 106
MYCODE:
class Solution:
def mergeSort(self, head):
if not head or not head.next:
return head
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
left = self.mergeSort(head)
right = self.mergeSort(mid)
return self.merge(left, right)
def merge(self, a, b):
dummy = Node(0)
t = dummy
while a and b:
if a.data < b.data:
t.next = a
a = a.next
else:
t.next = b
b = b.next
t = t.next
t.next = a or b
return dummy.next
explanation:
This program is done by merge sort method which is taught in class .
where there is two functions Merge and mergesort
The merge function is done using if else conditon and swapping the numberss if it is lesser than the previous number.
The mergesort function is used for the linked list where the merge function is used to sort the numbers.


Comments
Post a Comment