题解 | #合并两个排序的链表#
合并两个排序的链表
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* l1, struct ListNode* l2 ) { if(l1 ==NULL){ return l2; } if(l2 == NULL){ return l1; } struct ListNode* head = NULL,*tail = NULL; while(l1&&l2){ if(l1->val<l2->val){ if(head == NULL){ head = tail = l1; } else{ tail->next = l1; tail = l1; } l1 =l1->next; } else{ if(head == NULL){ head = tail = l2; } else{ tail->next = l2; tail = l2; } l2 =l2->next; } } if(l1 != NULL){ tail->next = l1; } if(l2 != NULL){ tail->next = l2; } return head; }