指针的操作比较繁琐复杂,需要捋清楚再写,中间犯了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;
}
};