/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null)
return head;
ListNode cur = head.next;
if (cur == null)
return head;
head.next = null;
ListNode h = head, head2 = new ListNode(-1);
head2.next = h;
while (cur != null) {
ListNode tmp = cur.next;
h = head2.next;
if (cur.val < h.val) {
// insert befor h
cur.next = h;
h = cur;
head2.next = h;
} else {
head2.next = h;
ListNode pre = h;
h = h.next;
while (h != null && cur.val >= h.val) {
pre = h;
h = h.next;
}
// insert after pre
pre.next = cur;
cur.next = h;
}
cur = tmp;
}
return head2.next;
}
}
思路:先回忆一下插入排序:最经典的方法是假设第一个是排好顺序了,为后面的每一个元素在排好序的空间找到正确的插入点即可。
题目中是链表实现,这里需要注意的是再链表中寻找正确的插入点。每次在链表中完成一个插入,都更新表头,方便下一轮搜索。
注意点:思路清楚,然后Java 的指针的使用方法。
Sort a linked list using insertion sort.