# MergeSort Linked List

Posted: 30 Jul, 2020

Difficulty: Moderate

#### For a given Singly Linked List of integers, sort the list using the 'Merge Sort' algorithm.

##### Input format :

```
The first and the only line of input contains the elements of the linked list separated by a single space.
```

##### Remember/Consider :

```
While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element
```

##### Output format :

```
The only line of output contains the sorted elements of the Singly Linked List in a row, separated by a single space.
```

##### Note:

```
You are not required to print the elements, just sort the elements and return the head to the updated Singly Linked List.
```

##### Constraints :

```
1 <= N <= 10^5
1 <= DATA <= 10^9
Where 'DATA' denotes the value of node of Linked List.
Time Limit: 1sec
```

Approach 1

- The idea is to take a recursive approach by calling the sort function on the left half and right half of the list.
- In order to do so, get the middle node and split the list into two halves. We can use a two-pointer technique to get the middle node by running a slow and a fast pointer.
- The idea here is to move both the slow and fast pointer simultaneously until fast reaches the end of the list.
- Here, for every single step slow takes, fast will make a jump twice of the slow pointer.
- When the fast pointer reaches the end of the list, the slow pointer will reach the middle of the list.
- Now you can split into two two lists, by taking slow's next or slow as the head of second list.
- Make sure to make the tail of first list null.

- We can now ask the sort function to sort the left and right halves of the list.
- We can assume the lists are now sorted, we now can use the merge two sorted list technique to merge the lists to eventually make the final sorted list and return the new head pointing to the list.

SIMILAR PROBLEMS

# Insertion In Circular Linked List

Posted: 21 Apr, 2022

Difficulty: Easy

# Insertion In A Singly Linked List

Posted: 22 Apr, 2022

Difficulty: Easy

# Remove Loop

Posted: 22 Apr, 2022

Difficulty: Moderate

# Deletion In Doubly Linked List

Posted: 22 Apr, 2022

Difficulty: Easy

# Insertion In Doubly Linked List

Posted: 24 Apr, 2022

Difficulty: Easy