Merge Sort for Linked List
Submissions: 4822   Accuracy:


  Difficulty: Easy   Marks: 2

Given Pointer/Reference to the head of a linked list, task is to Sort the given linked list using Merge Sort.

You need to complete the function splitList() and mergeList(), which will be called by the function mergeSort().

void mergeSort(struct node** headRef)
    struct node* head = *headRef;
    struct node* a, b;
    if ((head == NULL) || (head->next == NULL))
       return NULL;
    splitList(head, &a, &b); 
    *headRef = mergeList(a, b);

The spliList() function takes three input, head of the linked list and references to two pointers that are initially null. The function changes these pointers so that will point to the two new splitted lists, left and right halves respectively. The function splits the linked list in to two halves just like in standard merge sort and store the two new head in pointer a and b respectively. As the name suggests function mergeList will merge two linked lists, as in standard merge sort and should head pointer to of the new merged list. 

Note: If the length of linked list is odd, then the extra node should go in the first list while splitting.

There will be multiple test cases, for each test case function mergeSort() will be called separately. The only input to the function is the pointer/reference to the head of the linked list.

For each test, print the sorted linked list.



3 5 2 4 1
9 15 0
1 2 3 4 5
0 9 15

Note:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

** For More Input/Output Examples Use 'Expected Output' option **

Author: harshitsidhwa

Need help with your code? Please use, generate link and share the link here.

to report an issue on this page.