LeetCode 题解(41): Insertion Sort List

题目:

Sort a linked list using insertion sort.

题解:

class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if(!head)
            return head;
        
        ListNode *p = head->next;
        ListNode *pre = head;
        while(p)
        {
            ListNode *q = head;
            //先判断头节点是否大于当前节点值,如果是,改变头结点
            if( q->val > p->val )
            {
                pre->next = p->next;
                p->next = head;
                head = p;
                p = pre->next;
                continue;
            }
            
            ListNode* innerPre = q;
            q = q->next;
            //否则,找到第一个值大于或等于当前节点的节点,该节点前一个节点用innerPre表示
            while(q && q->val < p->val)
            {
                q = q->next;
                innerPre = innerPre->next;
            }
            //如果当前节点即为找到的第一个大于等于的节点,不进行任何操作
            if(q == p)
            {
                p = p->next;
                pre = pre->next;
                continue;
            }
            //否则,正常插入
            else{
                pre->next = p->next;
                p->next = innerPre->next;
                innerPre->next = p;
                p = pre->next;
            }
        }
        
        return head;
    }
};


你可能感兴趣的:(LeetCode,Algorithm,list,sort,insertion)