题目
Sort a linked list using insertion sort.
方法
public ListNode insertionSortList(ListNode head) {
//只有一个结点或者为空
if (head == null || head.next == null) {
return head;
}
ListNode top = new ListNode(0);
top.next = head;
ListNode cur = head.next;
head.next = null;
while (cur != null) {
ListNode help = cur.next;
ListNode list = top;
while (list.next != null && cur.val > list.next.val ) {
list = list.next;
}
if (list.next != null) {
cur.next = list.next;
list.next = cur;
} else {
list.next = cur;
cur.next = null;
}
cur = help;
}
return top.next;
}