您的位置:首页 > 其它

Insertion Sort List(leetcode)

2014-11-20 16:46 267 查看
题目:

Sort
a linked list using insertion sort.

题目来源:https://oj.leetcode.com/problems/insertion-sort-list/

解题思路:从第一个节点开始,逐步插入到比它大的第一个数前面,把原来的那个节点删除。

#include<iostream>
using namespace std;

struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

//把second插入到first之后
void insert(ListNode *first,ListNode *second)
{
ListNode *temp=first->next;
first->next=second;
second->next=temp;
}

ListNode *insertionSortList(ListNode *head)
{
if(head==NULL)
return NULL;
ListNode *first=new ListNode(INT_MIN);
first->next=head;
ListNode *curr=head,*prev=first,*prevCurr=first;
while(curr!=NULL)
{
prev=first;
ListNode *post=first;
while(post!=curr && post->val<curr->val)
{
prev=post;
post=post->next;
}
if(post!=curr)
{
prevCurr->next=prevCurr->next->next;//把curr节点删除
insert(prev,curr);
curr=prevCurr->next;
}
else
{
prevCurr=curr;
curr=curr->next;
}
}
return first->next;
}

int main()
{
ListNode *head=new ListNode(4);
head->next=new ListNode(2);
head->next->next=new ListNode(1);
head->next->next->next=new ListNode(3);
ListNode *result=insertionSortList(head);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: