124. Sort LL

Given the head of a singly linked list. Sort the values of the linked list in non-decreasing order and return the head of the modified linked list.

Example 1:

Input: head -> 5 -> 6 -> 1 -> 2 -> 1

Output: head -> 1 -> 1 -> 2 -> 5 -> 6

Explanation: 1 <= 1 <= 2 <= 5 <= 6

Example 2:

Input: head -> 6 -> 5 -> -1 -> -2 -> -3

Output: head -> -3 -> -2 -> -1 -> 5 -> 6

Explanation: -3 <= -2 <= -1 <= 5 <= 6

Now Your Turn!

Pick the correct output for the given input

Input: head -> -1 -> -2 -> -3 -> -1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= number of nodes in the linked list <= 1000
  • -104 <= ListNode.val <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/*
Definition of singly linked list:
struct ListNode
{
int val;
ListNode *next;
ListNode()
{
val = 0;
next = NULL;
}
ListNode(int data1)
{
val = data1;
next = NULL;
}
ListNode(int data1, ListNode *next1)
{
val = data1;
next = next1;
}
};
*/
 
class Solution {
public:
ListNode* sortList(ListNode* head) {
 
}
};
 
 
Test Case

Input:

Nums