插入排序来排序链表(时间复杂度O(n2))
/**
* 对链表进行插入排序 O(n^2)。 输入: 4->2->1->3 ,输出: 1->2->3->4
* 思路: pre pre.next head (head.next)cur
* 2 9 10 15 8
*/
public class LC147 {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre;
while (head != null && head.next != null) {
if (head.val < head.next.val) {
head = head.next;
continue;
}
pre = dummy;
ListNode cur = head.next;
while (pre.next.val < cur.val) {
pre = pre.next;
}
head.next = cur.next;
cur.next = pre.next;
pre.next = cur;
}
return dummy.next;
}
}
归并排序来排序链表(时间复杂度O(nlogn))
/**
* 思路:归并排序 O(n log n) O(1)
* 找出链表中间位置:设置一个慢指针slow,一个快指针fast
* 画图可知,fast != null 、fast.next != null 、fast.next.next == null 时
* 还需要往后走一次,所以终止条件为 fast != null && fast.next != null
*/
public class LC148 {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(tmp);
ListNode h = new ListNode(0);
ListNode res = h;
while (left != null && right != null) {
if (left.val < right.val) {
h.next = left;
left = left.next;
} else {
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left != null ? left : right;
return res.next;
}
}
通过比较147的插入排序(n2)和148的归并排序(nlogn),最好使用归并排序