题目:Insertion Sort List
难度:medium
问题描述:
使用插入排序对List进行排序
求解思路:
从左到右,依次将node插入到左边已经排好的list中
代码如下:
public static ListNode insertionSortList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode p = head.next;
head.next = null;
while(p!=null){
ListNode pnext = p.next;
ListNode q = head;
if(p.val<=q.val){
p.next = q;
head = p;
}else{
while(q!=null && q.next!=null && q.next.val<p.val){
q = q.next;
}
p.next = q.next;
q.next = p;
}
p = pnext;
}
return head;
}