Sort a linked list using insertion sort.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == NULL || head->next == NULL){
return head;
}
ListNode* cur = head->next;
ListNode* temp = NULL;
while(cur!=NULL){
temp = head;
while(temp->val < cur->val && temp != cur){
temp = temp->next;
}
if(temp != cur){
int first = cur->val;
int second ;
while(temp != cur){
second = temp->val;
temp->val = first;
first = second;
temp = temp->next;
}
temp->val = first;
}
cur = cur->next;
}
return head;
}
};