Insertion Sort List
Description
Sort a linked list using insertion sort.
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
public ListNode insertionSortList(ListNode head) {
// write your code here
ListNode dummy = new ListNode(0) ;
while(head != null){
ListNode tail = dummy ;
while(tail.next != null && tail.next.val < head.val){
tail = tail.next ;
}
ListNode temp = head.next ;
head.next = tail.next ;
tail.next = head ;
head = temp ;
}
return dummy.next ;
}
}