forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0148-sort-list.cs
49 lines (45 loc) · 1.17 KB
/
0148-sort-list.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Solution
{
public ListNode SortList(ListNode head)
{
if (head is null || head.next is null)
return head;
ListNode middle = GetMiddle(head);
ListNode left = head;
ListNode right = middle.next;
middle.next = null;
return Merge(SortList(left), SortList(right));
}
private ListNode GetMiddle(ListNode head)
{
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode Merge(ListNode left, ListNode right)
{
var head = new ListNode();
var tail = head;
while (left is not null && right is not null)
{
if (left.val < right.val)
{
tail.next = left;
left = left.next;
}
else
{
tail.next = right;
right = right.next;
}
tail = tail.next;
}
tail.next = left is not null ? left : right!;
return head.next;
}
}