-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution148.cs
59 lines (48 loc) · 1.18 KB
/
Solution148.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
50
51
52
53
54
55
56
57
58
59
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution148
{
/// <summary>
/// 148. Sort List - Medium
/// <a href="https://leetcode.com/problems/sort-list">See the problem</a>
/// </summary>
public ListNode SortList(ListNode head)
{
if (head?.next == null)
{
return head;
}
var slow = head;
var fast = head;
ListNode prev = null;
while (fast is { next: not null })
{
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev!.next = null;
return Merge(SortList(head), SortList(slow));
}
private ListNode Merge(ListNode l1, ListNode l2)
{
var dummy = new ListNode();
var curr = dummy;
while (l1 != null && l2 != null)
{
if (l1.val < l2.val)
{
curr.next = l1;
l1 = l1.next;
}
else
{
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
curr.next = l1 ?? l2;
return dummy.next;
}
}