Sort List
题目:
Sort a linked list in O(n log n) time using constant space complexity.
分析:
无
解法:quickSort
链表上的quickSort好难写,买没有学会
解法:mergeSort
public class Solution {
/**
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list,
using constant space complexity.
*/
public ListNode findMiddle(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
/*
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
*/
}
public ListNode merge(ListNode A, ListNode B) {
if (A == null && B == null) {
return null;
}
if (A == null) {
return B;
}
if (B == null) {
return A;
}
ListNode dummy = new ListNode(-1);
ListNode curr = dummy;
while (A != null && B != null) {
if (A.val < B.val) {
curr.next = A;
A = A.next;
} else {
curr.next = B;
B = B.next;
}
curr = curr.next;
curr.next = null;
}
if (A != null) {
curr.next = A;
}
if (B != null) {
curr.next = B;
}
return dummy.next;
}
public ListNode sortList(ListNode head) {
// write your code here
if (head == null || head.next == null) {
return head;
}
ListNode mid = findMiddle(head);
ListNode right = sortList(mid.next);
mid.next = null;
ListNode left = sortList(head);
return merge(left, right);
}
}