/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* H = NULL;
public:
ListNode* insert(ListNode* head,ListNode* t)
{
ListNode* p1 = new ListNode(INT_MIN);
p1->next = head;
ListNode* p = p1;
ListNode* r = NULL;
while(p)
{
r = p;
p = p->next;
if(!p || p->val >t->val)
{
r->next = t;
t->next = p;
return p1->next;
}
}
return head;
}
int print(ListNode* p)
{
int cnt = 0;
while(p)
{
cnt++;
cout<<p->val<<" ";
p = p->next;
}
cout<<endl;
return cnt;
}
ListNode* insertionSortList(ListNode* head) {
int num = print(head);
ListNode* p = head;
ListNode* r = NULL;
for(int i = 0;i<num;i++)
{
int flag = 0;
while(p)
{
if(p && r && p->val < r->val)
{
r->next = p->next;
flag = 1;
break;
}
r = p;
p = p->next;
}
if(flag)
{
head = insert(head,p);
p = r->next;
}
}
return head;
}
};