插入排序的思想是:依次读取链表当前值,将其插入之前已排序好的部分中的正确位置,不断的向向已排序的新链表中添加新的节点,并且保证添加节点后的列表仍然有序,直至原链表遍历完毕。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode node =new ListNode(-1);
node.next=head;
ListNode cur=head.next;
head.next=null;
while(cur!=null){
ListNode pre=node;
ListNode temp=cur.next;
while(pre.next!=null&&cur.val>pre.next.val){
pre=pre.next;
}
cur.next=pre.next;
pre.next=cur;
cur=temp;
}
return node.next;
}
}