Sort a linked list using insertion sort.
public ListNode insertionSortList(ListNode head) {
ListNode helper = new ListNode(0);
ListNode pre = helper;
ListNode cur =head;
ListNode next = null;
while(cur!=null){
next = cur.next;
while(pre.next!=null&&pre.next.val<cur.val){
pre = pre.next;
}
cur.next = pre.next;
pre.next = cur;
pre = helper;
cur = next;
}
return helper.next;
}
总结:新建一个新的linked list, 然后对于一个新的cur,寻找其插入位置的时候从helper开始,其实helper是无效的,helper.next才有效。