Insertion Sort List
Sort a linked list using insertion sort.
Subscribe to see which companies asked this question.
插入排序,注意指针的指向
代码:
/**
* 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) {
ListNode* first,*second;
ListNode* hhead;
if (head==NULL) return NULL;
first=head;
hhead=new ListNode(INT_MIN);
second=hhead;
hhead->next=head;
ListNode* cur=head->next;
head->next=NULL;
int len=1;
while(cur)
{
ListNode* temp=cur->next;
cur->next=NULL;
second=hhead;
first=second->next;
int flag=0;
for (int i=0; i<len; i++)
{
if (((cur->val)>=(second->val))&&((cur->val)<=(first->val)))
{
cur->next=first;
second->next=cur;
flag=1;
break;
}
else
{
second=first;
first=first->next;
}
}
if (flag==0)
{
second->next=cur;
}
cur=temp;
len++;
}
return hhead->next;
}
};