/** 147. Insertion Sort List * 2016-6-1 by Mingyang * Insertion Sort The basic idea is to have, the more ingenious point is, every time you handle a point, put the following point in the next to save it. Next can be processed directly, and then the second while loop inside only contains one case, and the other is a break * it doesn't actually have to be written down.*/ PublicListNode insertionsortlist (ListNode head) {if(Head = =NULL) { returnHead; } ListNode Helper=NewListNode (0);//new starter of the sorted listListNode cur = head;//The node would be insertedListNode pre = helper;//Insert node between pre and Pre.nextListNode next =NULL;//The next node would be inserted//Not the end of the input list while(cur! =NULL) {Next=Cur.next; //find the right place to insert while(Pre.next! =NULL&& Pre.next.val <cur.val) {Pre=Pre.next; } //insert between pre and Pre.nextCur.next =Pre.next; Pre.next=cur; //let the pre and cur return to their original positionsPre =Helper; Cur=Next; } returnHelper.next; }
147. Insertion Sort List