-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path148.SortList.cs
50 lines (48 loc) · 1.15 KB
/
148.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
public class Solution {
public ListNode SortList(ListNode head) {
if (head == null || head.next == null)
{
return head;
}
ListNode p1 = null;
var p2 = head;
while (p2 != null)
{
p2 = p2.next;
if (p2 != null)
{
p2 = p2.next;
p1 = p1 == null ? head : p1.next;
}
}
p2 = p1.next;
p1.next = null;
p1 = head;
p1 = SortList(p1);
p2 = SortList(p2);
ListNode newHead = null;
ListNode newTail = null;
while (p1 != null || p2 != null)
{
if (p1 == null || (p2 != null && p1.val > p2.val))
{
var temp = p1;
p1 = p2;
p2 = temp;
}
var next = p1;
p1 = p1.next;
next.next = null;
if (newTail == null)
{
newHead = newTail = next;
}
else
{
newTail.next = next;
newTail = next;
}
}
return newHead;
}
}