Sort a linked list using insertion sort.
Subscribe to see which companies asked this question.
/**
* 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 head;
ListNode cur=head.next;
ListNode find=head;
int preval=head.val;
while(cur!=null){
if(cur.val<preval){
while(find.val<=cur.val)
find=find.next;
int insert=cur.val;
int temp=find.val;
while(find.val!=cur.val){
temp=find.val;
find.val=insert;
insert=temp;
find=find.next;
}
cur.val=insert;
find=head;
}
preval=cur.val;
cur=cur.next;
}
return head;
}
}