思路:用一个新链表来执行插入排序,将新的节点插入到正确的位置;
代码:
public ListNode insertionSortList(ListNode head){
if (head==null||head.next==null)return head;
ListNode temp=new ListNode(Integer.MIN_VALUE);
ListNode now=temp;
ListNode cur=head;
while (cur!=null){
now=temp;//每次都从第一个节点开始比较
ListNode next=cur.next;//选取要排序的链表的下一个节点
while (now.next!=null&&now.next.val<cur.val){//判断要选取插入的位置
now=now.next;
}
cur.next=now.next;//插入节点
now.next=cur;//插入节点
cur=next;
}
return temp.next;//摒弃第一个自己new的节点
}