您的位置:首页 > 其它

147. Insertion Sort List

2016-04-10 20:48 405 查看
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
//80 ms
class Solution {
public:
ListNode* insertion(ListNode* temp,ListNode* head)
{
if(temp->val<head->val)
{
temp->next=head;
return temp;
}
ListNode* a=head;
while(a->next&&a->next->val<temp->val) a=a->next;
if(!a->next)
{
temp->next=NULL;
a->next=temp;
}
else
{
temp->next=a->next;
a->next=temp;
}
return head;
}
ListNode* insertionSortList(ListNode* head) {
if(!head) return head;
ListNode* temp1=head->next;
ListNode* head0=head;
head0->next=NULL;
while(temp1)
{
ListNode* temp=temp1->next;
head0=insertion(temp1,head0);
temp1=temp;
}
return head0;
}
};


//80ms
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(!head) return head;
ListNode myhead(INT_MIN),*cur,*temp;
while(head)
{
for(cur=&myhead;cur->next&&cur->next->val<head->val;) cur=cur->next;
temp=head->next;
head->next=cur->next;
cur->next=head;
head=temp;
}
return myhead.next;
}
};


//24ms
//即使是插入排序,也不需要每次都从头查找
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(!head) return head;
ListNode myhead(INT_MIN),*cur=&myhead,*temp;
while(head)
{
if(head->val<cur->val) cur=&myhead;
for(;cur->next&&cur->next->val<head->val;) cur=cur->next;
temp=head->next;
head->next=cur->next;
cur->next=head;
head=temp;
}
return myhead.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: