Sort a linked list using insertion sort.
linked list 的insertion sort,需要记住第一个node,以后的每一个curnode从第一个往后放到合适的位置。代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return head;
}
ListNode helper = new ListNode(0);
ListNode prev = helper;
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
if (prev == null || prev.next == null || prev.next.val > cur.val) {
prev = helper;
}
while (prev.next != null && prev.next.val < cur.val) {
prev = prev.next;
}
cur.next = prev.next;
prev.next = cur;
//prev = helper;
cur = next;
}
return helper.next;
}
}