Sort a linked list using insertion sort.
Subscribe to see which companies asked this question
思路一:常规做法,将链表头结点拆开(head->next=null)来做待返回的新的有序链表的头,从头结点的下一个开始遍历每个结点往这个新的有序链表中添加
/**
* 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* cNode=head->next;
head->next=NULL;
while(cNode!=NULL)
{
ListNode* pNext=cNode->next;
//cNode->next=NULL;
head=insertList(head,cNode);
cNode=pNext;
}
ListNode* tmp=head;
while(tmp){
cout<<tmp->val<<" ";
tmp=tmp->next;
}
return head;
}
private:
ListNode* insertList(ListNode* head,ListNode* cNode)
{
if(head==NULL)
{
cNode->next=NULL;
return cNode;
}
if(head->val>=cNode->val)
{
cNode->next=head;
return cNode;
}
ListNode* tmp=head->next;
ListNode* pre=head;
while(tmp!=NULL && cNode->val>tmp->val)
{
pre=tmp;
tmp=tmp->next;
}
pre->next=cNode;
cNode->next=tmp;
return head;
}
};
思路二:链表先不拆开,从头往后遍历,
相邻两个结点比较,判断不符合升序排列的结点cNode->next,把
cNode->next结点挪到合适位置
这样就避免了思路一中的每个结点都要与新的有序链表从头比较.新建一个头结点可以避免新插入的结点是第一个时要判断更新头
class Solution {
public:
ListNode* insertionSortList(ListNode* head)
{
if( head==NULL || head->next==NULL)
return head;
ListNode* newNode=new ListNode(0);
ListNode* pre=newNode;
newNode->next=head;
ListNode* cNode=head;
while(cNode!=NULL)
{
if(cNode->next && cNode->val > cNode->next->val)
{
while(pre->next && pre->next->val<cNode->next->val)
pre=pre->next;
ListNode* tmp=cNode->next->next;
cNode->next->next=pre->next;
pre->next=cNode->next;
cNode->next=tmp;
pre=newNode;
}
else
{
cNode=cNode->next;
}
}
head=newNode->next;
delete newNode;
return head;
}
};