Sort a linked list using insertion sort.
/**
* 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 || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = head;
ListNode curr = head.next;
while (curr != null) {
ListNode p1 = dummy;
ListNode p2 = dummy.next;
while (p2 != curr) {
if (p2.val > curr.val) {
pre.next = curr.next;
p1.next = curr;
p1.next.next = p2;
curr = pre.next;
break;
} else {
p1 = p2;
p2 = p1.next;
}
}
if (p2 == curr) {
pre = curr;
curr = pre.next;
}
}
return dummy.next;
}
}