题目描述
Sort a linked list using insertion sort.
对链表进行插入排序
题目解析
插入排序的方法是首先构造出一个与head值相同的结点res,比较该结点的值和head后面结点cur的值,若小于head,则cur指向
res,res赋值为cur。否则将cur插入到res后面的结点中。
代码如下
/**
* 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)
return head;
ListNode res = new ListNode(head.val);
ListNode left = head.next;
while ((left!=null)){
ListNode cur = left;
left = left.next;
//比较头
if(cur.val <= res.val){
cur.next = res;
res = cur;
continue;
}
//在res中寻找插入点
ListNode p = res;
ListNode last = p;
while (p!=null&&p.val<cur.val){
last = p;
p = p.next;
}
last.next = cur;
cur.next = p;
}
return res;
}
}