class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1 == NULL && pHead2 == NULL) return NULL; if(pHead1 == NULL){ return pHead2; } if(pHead2 == NULL){ return pHead1; } ListNode *Head = NULL; ListNode *p = NULL; while(pHead1 && pHead2){ if(pHead1->val <= pHead2->val){ if(Head == NULL){ Head = p = pHead1; }else{ p->next = pHead1; p = p->next; } pHead1 = pHead1->next; } //這里必須是else,因為第一步當中指針操作之后可能也滿足第二個if,所以兩個if不行 else if(pHead1->val > pHead2->val){ if(Head == NULL){ Head = p = pHead2; }else{ p->next = pHead2; p = p->next; } pHead2 = pHead2->next; } } if(pHead1 == NULL){ p->next = pHead2; } if(pHead2 == NULL){ p->next = pHead1; } return Head; } };
記錄一下踩的坑。注釋處必須是else,如果倆if就報錯