题目描述
Sort a linked list using insertion sort.
public class l147_insertion_sort_list {
class ListNode{
int val;
ListNode next;
ListNode(int x){
this.val=x;
next=null;
}
}
public ListNode insertionSortList(ListNode head) {
if(head==null) return head;
ListNode h=new ListNode(Integer.MIN_VALUE);//新建一个链表头节点
h.next=head;
ListNode cur=head.next; //保存当前处理节点
head.next=null; //新链表暂时无数据
while (cur!=null){
ListNode curnext=cur.next;//保存下一个要处理的节点
ListNode pre=h;
ListNode pos=h.next;//待插入位置
while (pos!=null)
{
if(pos.val<cur.val){
pre=pos;
pos=pos.next;
}
else {
//找到插入位置,进行插入操作
break;
}
}
//插入节点
cur.next=pre.next;
pre.next=cur;
cur=curnext;
}
return h.next;
}
}