Sort a linked list using insertion sort.
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// usding dummy head to simplify
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode curt = head.next;
head.next = null;
while (curt != null) {
ListNode nodeToInsert = curt;
curt = curt.next;
nodeToInsert.next = null;
// iterate sort list
ListNode prev = dummyHead;
ListNode n = dummyHead.next;
while (n != null) {
if (nodeToInsert.val <= n.val) {
prev.next = nodeToInsert;
nodeToInsert.next = n;
break;
} else {
prev = n;
n = n.next;
}
}
// 之前都没有比上,一直到 n == null
// attach 到 sort list 队尾
if (n == null) {
prev.next = nodeToInsert;
}
}
return dummyHead.next;
}
思路比较简单,就是用 insertion sort 的方法套用到 liked list 上。
一个新的node添加到队头的情况用 dummy head 可以方便地解决。
添加到队尾的情况就是对应于 (n == null),说明需要添加到队尾