[leedcode 147] Insertion Sort List
Sort a linked list using insertion sort.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { //插入排序,时间复杂度O(n^2),注意终止条件,默认p之前的已经从小到大排好序了 public ListNode insertionSortList(ListNode head) { if(head==null||head.next==null) return head; ListNode newHead=new ListNode(-1); newHead.next=head; ListNode p=head.next; ListNode ppre=head; boolean flag=false; while(p!=null){/// if(p.val>ppre.val){// p=p.next; ppre=ppre.next; }else{ ListNode q=newHead.next; ListNode qpre=newHead; while(q.val<p.val){ qpre=qpre.next; q=q.next; } ppre.next=p.next; qpre.next=p; p.next=q; p=ppre.next; } } return newHead.next; } }