-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0148-SortList.cs
69 lines (59 loc) · 1.82 KB
/
0148-SortList.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
60
61
62
63
64
65
66
67
68
69
//-----------------------------------------------------------------------------
// Runtime: 108ms
// Memory Usage: 31 MB
// Link: https://leetcode.com/submissions/detail/408465342/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class _0148_SortList
{
public ListNode SortList(ListNode head)
{
if (head == null || head.next == null) return head;
ListNode prev = null, slow = head, fast = head;
while (fast != null && fast.next != null)
{
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
var left = SortList(head);
var right = SortList(slow);
return Merge(left, right);
}
private ListNode Merge(ListNode left, ListNode right)
{
var dummy = new ListNode();
var current = dummy;
while (left != null && right != null)
{
if (left.val < right.val)
{
current.next = left;
left = left.next;
}
else
{
current.next = right;
right = right.next;
}
current = current.next;
}
if (left != null) current.next = left;
if (right != null) current.next = right;
return dummy.next;
}
}
}