Skip to content

Commit cad4b0d

Browse files
committed
create 0148-sort-list.cs
1 parent 3261f51 commit cad4b0d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Diff for: csharp/0148-sort-list.cs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
public class Solution
2+
{
3+
public ListNode SortList(ListNode head)
4+
{
5+
if (head is null || head.next is null)
6+
return head;
7+
8+
ListNode middle = GetMiddle(head);
9+
ListNode left = head;
10+
ListNode right = middle.next;
11+
middle.next = null;
12+
13+
return Merge(SortList(left), SortList(right));
14+
}
15+
private ListNode GetMiddle(ListNode head)
16+
{
17+
ListNode slow = head;
18+
ListNode fast = head.next;
19+
while (fast != null && fast.next != null)
20+
{
21+
slow = slow.next;
22+
fast = fast.next.next;
23+
}
24+
return slow;
25+
}
26+
private ListNode Merge(ListNode left, ListNode right)
27+
{
28+
var head = new ListNode();
29+
var tail = head;
30+
while (left is not null && right is not null)
31+
{
32+
if (left.val < right.val)
33+
{
34+
tail.next = left;
35+
left = left.next;
36+
}
37+
else
38+
{
39+
tail.next = right;
40+
right = right.next;
41+
}
42+
tail = tail.next;
43+
}
44+
45+
tail.next = left is not null ? left : right!;
46+
47+
return head.next;
48+
}
49+
}

0 commit comments

Comments
 (0)