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;
}
};