问题描述:如题
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode curr=head.next;
//遍历链表,每次取出一个节点,在前面已经排好序的部分中找到合适的位置将它插进去
while(curr!=null){
ListNode pre=dummy;
ListNode temp=pre.next;
ListNode next=curr.next;
while(temp!=null && temp.val<curr.val){
pre=temp;
temp=temp.next;
}
pre.next=curr;
curr.next=temp;
if(temp!=null && temp.next==curr){//相当于在对前两个元素排序时,对排序好的链表进行封口,之后就不用了
temp.next=null;//相当于封口
}
curr=next;
}
return dummy.next;
}
}