[LeetCode] 148. 排序链表
用归并排序一个链表。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
return sortList(head, null);
}
public ListNode sortList(ListNode head, ListNode tail) {
if (head == null) {
return head;
}
if (head.next == tail) {
head.next = null;
return head;
}
ListNode slow = head, fast = head;
while (fast != tail) {
slow = slow.next;
fast = fast.next;
if (fast != tail) {
fast = fast.next;
}
}
ListNode mid = slow;
ListNode list1 = sortList(head, mid);
ListNode list2 = sortList(mid, tail);
ListNode sorted = merge(list1, list2);
return sorted;
}
private ListNode merge(ListNode head1, ListNode head2) {
ListNode ret = new ListNode(0);
ListNode tmp = ret;
while (head1 != null && head2 != null) {
if (head1.val > head2.val) {
tmp.next = head2;
head2 = head2.next;
} else {
tmp.next = head1;
head1 = head1.next;
}
tmp = tmp.next;
}
if (head1 != null) tmp.next = head1;
if (head2 != null) tmp.next = head2;
return ret.next;
}
}