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 newhead = new ListNode(0);
newhead.next = head;
ListNode p, q, r;
p = head;
while((p != null)&&(p.next != null)){
if(p.val <= p.next.val)
p = p.next;
else{
q = p.next;
p.next = q.next;
r = newhead;
while(r.next.val <= q.val){
r = r.next;
}
q.next = r.next;
r.next = q;
}
}
return newhead.next;
}
}