您的位置:首页 > 其它

LeetCode_Insertion Sort List

2014-05-06 20:48 309 查看
Sort a linked list using insertion sort.

这道题简单,就是使用插入排序的方式对链表进行排序,主要就是链表的基本操作。

需要注意的几点:

每步插入操作存在一下三种情况:

//case 1:if position is head

//case 2:position is not pCurrent

//case 3:position is between head and pCurrent

也就是说需要插入的位置(position)不同,可能导致操作也就不同,这一点与针对于数组的插入操作不同。

代码中描述的很清楚。

class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (head==NULL)
{
return NULL;
}
if (head->next==NULL)
{
return head;
}

//insert sort
ListNode* pCurrent;
ListNode* pPreCurrent;
pPreCurrent=head;
pCurrent=head->next;
while (pCurrent!=NULL)
{
ListNode* pPreCompare=NULL;
ListNode* pCompare=head;
//find position
while (pCompare!=pCurrent)
{
if (pCompare->val>pCurrent->val)
{
break;
}
pPreCompare=pCompare;
pCompare=pCompare->next;
}

//case 1:if position is head
if (pCompare==head)
{
//cut the pCurrent
pPreCurrent->next=pCurrent->next;

//change head and insert
pCurrent->next=head;
head=pCurrent;

//change next  pCurrent
pCurrent=pPreCurrent->next;
}
else
{
//case 2:position is not pCurrent
if (pCompare==pCurrent)
{
//change pCurrent and pPreCurrent
pPreCurrent=pCurrent;
pCurrent=pCurrent->next;
}
else
{
//case 3:position  is between head and pCurrent
//cut pCurrent
pPreCurrent->next=pCurrent->next;

//insert pCurrent to position
pCurrent->next=pCompare;
pPreCompare->next=pCurrent;

//change next pCurrent
pCurrent=pPreCurrent->next;
}
}
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: