LeetCode 147:对链表进行插入排序

指针的操作比较繁琐复杂,需要捋清楚再写,中间犯了3个错误: 

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(!head || !head->next) return head; //Bug2:不应该是nullptr,应该是head

        ListNode* dummy = new ListNode(-1);
        dummy->next = head; //Bug0:dummy节点忘记和head接起来

        ListNode* pFirst, *pSecond, *pPre = head, *pCur = head->next;

        while(pCur) {
            if(pCur->val < pPre->val) {
                pFirst = dummy; pSecond = dummy->next; //Bug1:因为一开始写成了head,实际的head指针在一直往后移,真正的head应该是dummy之后
                while(pSecond && pSecond->val <= pPre->val && pCur->val > pSecond->val) {
                    pFirst = pSecond;
                    pSecond = pSecond->next;
                }
                pFirst->next = pCur;
                pPre->next = pCur->next;
                pCur->next = pSecond;

                pCur = pPre->next;
            }
            else {
                pPre = pCur;
                pCur = pCur->next;
            }
        }

        ListNode* res = dummy->next;
        delete dummy;
        return res;
    }
};
发布了97 篇原创文章 · 获赞 11 · 访问量 2457

猜你喜欢

转载自blog.csdn.net/chengda321/article/details/104441674