ExamAdda Logo

Sort List

Easy

Given the head of a singly linked list, sort the linked list in ascending order and return the sorted list.

The solution should sort the linked list efficiently.

Example 1

Input

n = 4
nums = [4, 2, 1, 3]

Output

1 2 3 4

Explanation

The linked list:

4 → 2 → 1 → 3

 

is sorted into:

1 → 2 → 3 → 4

Example 2

Input

n = 5
nums = [-1, 5, 3, 4, 0]

Output

-1 0 3 4 5

Explanation

The elements are rearranged in ascending order.

Constraints

0 <= number of nodes <= 5 * 10^4
-10^5 <= Node.val <= 10^5
The linked list may contain duplicate values.
The result must be sorted in ascending order.

Hints:

Hint 1

A linked list does not support random access efficiently, so avoid approaches that repeatedly access elements by index.

Hint 2

Use Merge Sort: split the linked list into two halves, recursively sort both halves, and merge them.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 22, 2026

Last updated

Aug 22, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output