Sort a linked list using insertion sort.
分析:插入排序处理链表。借助一个helper 头节点,来避免比较过程中插入位置在头节点处的情况。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode initNode = new ListNode(head.val);
ListNode fakeHead = new ListNode(-1);
fakeHead.next = initNode;
ListNode fakeCursor = fakeHead;
head = head.next;
ListNode cursor = head;
while (cursor != null) {
while (fakeCursor.next != null && cursor.val >= fakeCursor.next.val) {
fakeCursor = fakeCursor.next;
}
head = cursor.next;
if (fakeCursor.next != null) {
cursor.next = fakeCursor.next;
fakeCursor.next = cursor;
} else {
fakeCursor.next = cursor;
cursor.next = null;
}
cursor = head;
fakeCursor = fakeHead;
}
return fakeHead.next;
}
}