Sort a linked list using insertion sort.
Simply insert the sort, write a function that inserts a value into the list, and then traverse the entire list, one by one inserting the value into the new list:
1 PublicListNode insertionsortlist (ListNode head) {2 if(head==NULL)3 return NULL;4ListNode re =NewListNode (head.val);5ListNode cur =Head.next;6 while(cur!=NULL)7 {8Re =Insert (Re, cur.val);9Cur =Cur.next;Ten } One returnre; A } - - PublicListNode Insert (ListNode Head,intv) the { -ListNode LN =NewListNode (v); -ListNode cur =head; -ListNode helper =NewListNode (0); +Helper.next =head; -ListNode pre =Helper; + A while(cur!=NULL) at { - if(v<cur.val) - { -Pre.next =Ln; -Ln.next =cur; - returnHelper.next; in } -Pre =cur; toCur =Cur.next; + } -Pre.next =Ln; theLn.next =NULL; * returnHelper.next; $}
Recursive implementations:
1 PublicListNode insertionsortlist (ListNode head) {2 if(head==NULL|| head.next==NULL)3 returnhead;4 intValue =Head.val;5 returnInsert (Insertionsortlist (Head.next), value);6 }7 8 PublicListNode Insert (ListNode Head,intv)9 {TenListNode LN =NewListNode (v); OneListNode cur =head; AListNode helper =NewListNode (0); -Helper.next =head; -ListNode pre =Helper; the - while(cur!=NULL) - { - if(v<cur.val) + { -Pre.next =Ln; +Ln.next =cur; A returnHelper.next; at } -Pre =cur; -Cur =Cur.next; - } -Pre.next =Ln; -Ln.next =NULL; in returnHelper.next; -}
[Leetcode] [JAVA] Insertion Sort List