You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given the `head` of a linked list, return *the list after sorting it in **ascending order***.
9
2
10
3
**Example 1:**
11
-
```
4
+
5
+
```tex
12
6
Input: head = [4,2,1,3]
13
7
Output: [1,2,3,4]
14
8
```
15
9
16
10
**Example 2:**
17
-
```
11
+
12
+
```tex
18
13
Input: head = [-1,5,3,4,0]
19
14
Output: [-1,0,3,4,5]
20
15
```
21
16
22
17
**Example 3:**
23
-
```
18
+
19
+
```tex
24
20
Input: head = []
25
21
Output: []
26
22
```
@@ -66,17 +62,20 @@ Let's break down the solution step by step:
66
62
- Set `slow.next = None` to split the list
67
63
68
64
**Step 4: Recursively sort halves**
65
+
69
66
- Sort the left half: `left = sortList(head)`
70
67
- Sort the right half: `right = sortList(mid)`
71
68
72
69
**Step 5: Merge the sorted halves**
70
+
73
71
- Use a dummy node to simplify merging
74
72
- Compare nodes from both lists and link them in order
75
73
76
74
**Example walkthrough:**
75
+
77
76
Let's trace through the first example:
78
77
79
-
```
78
+
```tex
80
79
head = [4,2,1,3]
81
80
82
81
Step 1: Find middle
@@ -101,64 +100,5 @@ result = [1,2,3,4]
101
100
102
101
> **Note:** Merge sort is ideal for linked lists because we can split and merge in-place without extra space. The fast/slow pointer technique efficiently finds the middle, and the merge step can be done by simply relinking nodes.
0 commit comments