题解 | 合并两个排序的链表
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
//创建一个新的虚拟头节点,简化边界处理
struct ListNode dummy;
struct ListNode* current = &dummy;
//同时遍历两个链表
while (pHead1 != NULL && pHead2 != NULL) {
if (pHead1->val <= pHead2 ->val) {
current->next = pHead1;
pHead1 = pHead1->next;
} else {
current->next = pHead2;
pHead2 = pHead2->next;
}
current = current->next;
}
// 将剩余的节点连接到结果链表
if (pHead1 != NULL) {
current->next = pHead1;
} else {
current->next = pHead2;
}
// 返回真正的头节点
return dummy.next;
}
OPPO公司福利 1225人发布