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 )
return head;
ListNode h1 = new ListNode(0);
ListNode current = null;
ListNode temp = null;
temp = head;
head = head.next;
temp.next = null;
h1.next = temp;
while( head!=null ){
current = h1;
while( current.next!=null && current.next.val<head.val ){
current = current.next;
}
if( current.next==null ){
temp = head;
head = head.next;
temp.next = null;
current.next = temp;
}else{
temp = head;
head = head.next;
temp.next = current.next;
current.next = temp;
}
}
return h1.next;
}
}