Sort a linked list using insertion sort.
public class Whynot {
public ListNode insertionSortList(ListNode head) {
if (head == null){
return null;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = head;
ListNode p = head.next;
ListNode h;
while (p != null) {
h = dummy; //每次循环都将h重新赋值为头结点,将p依次与h.next进行比较
while (h.next != p) {
if (h.next.val < p.val) {
h = h.next;
} else { //若当前h.next比p值大,则将p插入h与h.next之间
pre.next = p.next;
p.next = h.next;
h.next = p;
p = pre; //插入之后,将当前pre赋给p,继续循环
break;
}
}
pre = p;
if (p != null) {
p = p.next;
}
}
return dummy.next;
}
}