题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2) { if(pHead1 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; struct ListNode* RL = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* RLr = NULL; RL->next = RLr; struct ListNode* q1 = pHead1; struct ListNode* q2 = pHead2; while(q1 && q2) { if(q1->val <= q2->val) { if(RLr == NULL) { RL->next = q1; RLr = q1; } else { RLr->next = q1; RLr = q1; } q1 = q1->next; } else { if(RLr == NULL) { RL->next = q2; RLr = q2; } else { RLr->next = q2; RLr = q2; } q2 = q2->next; } } if(q1 == NULL) RLr->next = q2; if(q2 == NULL) RLr->next = q1; return RL->next; }
c语言很不容易啊,最后死在空指针发生段错误,一定注意判空条件放在最开始,规范书写