Sort a linked list using insertion sort.
/**
* 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 null;
}
ListNode helper = new ListNode(0);
ListNode curr = head, prev = helper, next = null;
while (curr != null) {
next = curr.next;
while (prev.next != null && prev.next.val < curr.val) {
prev = prev.next;
}
curr.next = prev.next;
prev.next = curr;
prev = helper;
curr = next;
}
return helper.next;
}
}