Insertion Sort List

来源:互联网 发布:绘画软件 编辑:程序博客网 时间:2024/06/05 23:42

Sort a linked list using insertion sort.

链表的插入排序。

排序直接在原链表上进行,要记下前驱pre和cur,

并且维护每次排序好之后的order_start和order_end,这样比较方便操作。


ListNode *insertionSortList(ListNode *head){    if(head == NULL || head->next == NULL)        return head;    ListNode *cur = head->next, *order_start = new ListNode(0), *order_end = head;    order_start->next = head;    while(cur != NULL)    {        ListNode *tmp = order_start->next, *pre = order_start;        while(tmp != cur && cur->val >= tmp->val)        {            tmp = tmp->next;            pre = pre->next;        }        if(tmp != cur)//插入到中间        {            order_end->next = cur->next;            cur->next = tmp;            pre->next = cur;        }        else//插入到最后        {            order_end = cur;        }        cur = order_end->next;    }    head = order_start->next;    return head;}


0 0