LeetCode-147. 链表插入排序

/**
 * 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 *daicharu=head->next,*tail,*p=head,*pre=NULL,*temp=NULL;
        while(p&&daicharu&&p->val<=daicharu->val)
        {//第一个优化,初始化待插入的节点开始位置
            p=p->next;
            daicharu=daicharu->next;
        }
        tail=p;
        p->next=NULL;
        while(daicharu)
        {
            p=head;
            pre=NULL;//p的前节点,开始为首节点的前一个节点NULL
            temp=daicharu;
            daicharu=daicharu->next;
            if(temp->val>=tail->val)
            {//第二个优化,大于尾节点,直接接上就可以了
                tail->next=temp;
                tail=temp;
                tail->next=NULL;
                continue;//插入下一个元素
            }
            //否则从头开始找位置
            while(p&&temp->val>=p->val){
                pre=p;
                p=p->next;
            }
            if(pre!=NULL)
            {//插在最前面
                pre->next=temp;
                temp->next=p;
                pre=pre->next;
            }else
            {//普通情况
                temp->next=p;
                pre=temp;
                head=pre;
            }
        }
        return head;
    }
};
posted @ 2020-11-21 15:49  ecnu_lxz  阅读(89)  评论(0)    收藏  举报