题解 | #合并两个排序的链表#
合并两个排序的链表
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 && pHead2 == NULL) return NULL; struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode) * 1); struct ListNode* dumy = res; struct ListNode* l1 = pHead1; struct ListNode* l2 = pHead2; while (l1 != NULL && l2 != NULL) { struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode) * 1); if (l1->val < l2->val) { node->val = l1->val; l1 = l1->next; } else { node->val = l2->val; l2 = l2->next; } res->next = node; res = res->next; } res->next = l1 == NULL ? l2 : l1; return dumy->next; }