-
Notifications
You must be signed in to change notification settings - Fork 118
/
SortList.java
60 lines (47 loc) · 1.4 KB
/
SortList.java
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
package Algorithms;
public class SortList {
public static void main(String[] str) {
SortList sl = new SortList();
ListNode head = new ListNode(1);
sl.sortList(head);
}
public ListNode sortList(ListNode head) {
if (head == null) {
return head;
}
ListNode mid = findMid(head);
ListNode right = sortList(mid.next);
mid.next = null;
ListNode left = sortList(head);
return merge(left, right);
}
private ListNode findMid(ListNode head) {
ListNode s = head;
ListNode f = head.next;
while (f != null && f.next != null) {
s = s.next;
f = f.next.next;
}
return s;
}
private ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
tail.next = head1;
head1 = head1.next;
} else {
tail.next = head2;
head2 = head2.next;
}
tail = tail.next;
}
if (head1 != null) {
tail.next = head1;
} else {
tail.next = head2;
}
return dummy.next;
}
}