Insertion Sort List
Sort a linked list using insertion sort.
對鏈表使用插入排序。
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(!head)
{
return NULL;
}
ListNode *tempHead = new ListNode(0);//新建臨時頭結點
tempHead->next = head;
ListNode *s = NULL, *cur = NULL;
ListNode *pre = head, *p = head->next;
while(p)
{
if(p->val >= pre->val)//當前節點值大於前一個節點值,則按序
{
p = p->next;
pre = pre->next;
}
else//比前一個節點小
{
cur = p;
p = p->next;
pre->next = p;
s = tempHead; //pre 重新指向表頭
while(s->next->val < cur->val)//找到在已排好鏈表中按序所在的位置
{
s = s->next;
}
cur->next = s->next;
s->next = cur;
}
}
head = tempHead->next;
delete tempHead; //刪除臨時頭結點
return head;
}
};