Merge Sort on Doubly Linked List
Medium Accuracy: 60.43% Submissions: 9631 Points: 4
Given Pointer/Reference to the head of a doubly linked list of N nodes, the task is to Sort the given doubly linked list using Merge Sort in both non-decreasing and non-increasing order.
Example 1:
Input:
N = 8
value[] = {7,3,5,2,6,4,1,8}
Output:
1 2 3 4 5 6 7 8
8 7 6 5 4 3 2 1
Explanation: After sorting the given
linked list in both ways, resultant
matrix will be as given in the first
two line of output, where first line
is the output for non-decreasing
order and next line is for non-
increasing order.
Example 2:
Input:
N = 5
value[] = {9,15,0,-1,0}
Output:
-1 0 0 9 15
15 9 0 0 -1
Explanation: After sorting the given
linked list in both ways, the
resultant list will be -1 0 0 9 15
in non-decreasing order and
15 9 0 0 -1 in non-increasing order.
Your Task:
The task is to complete the function sortDoubly() which sorts the doubly linked list. The printing is done automatically by the driver code.
#User function Template for python3
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
'''
#Function to sort the given doubly linked list using Merge Sort.
def split(head):
slow = head
fast = head.next
# Advance 'fast' by two nodes, and advance 'slow' by single node
while fast:
fast = fast.next
if fast:
slow = slow.next
fast = fast.next
return slow
# Recursive function to merge nodes of two sorted lists together
# into a single sorted list
def merge(a, b):
# Base cases
if a is None:
return b
if b is None:
return a
# Pick either a or b, and recur
if a.data <= b.data:
a.next = merge(a.next, b)
a.next.prev = a
a.prev = None
return a
else:
b.next = merge(a, b.next)
b.next.prev = b
b.prev = None
return b
# Function to sort a doubly linked list using merge sort algorithm
def sortDoubly(head):
# base case: 0 or 1 node
if head is None or head.next is None:
return head
# split head into 'a' and 'b' sublists
a = head
slow = split(head)
b = slow.next
slow.next = None
# recursively sort the sublists
a = sortDoubly(a)
b = sortDoubly(b)
# merge the two sorted lists together
head = merge(a, b)
return head
Comments
Post a Comment