- 有至少一个链表为空
if (pHead1 == NULL) return pHead2;
if (pHead2 == NULL) return pHead1;
- 定义虚拟头节点,存放结果
ListNode* result = new ListNode(0);
result->next = pHead1;
ListNode* cur = result;
- 当节点不为空时,比较两个节点值大小
while (p1 != NULL && p2 != NULL) {
if (p1->val < p2->val) {
cur->next = p1;
cur = cur->next;
p1 = p1->next;
}
else {
cur->next = p2;
cur = cur->next;
p2 = p2->next;
}
}
- 有残余项时
if (p1 != NULL && p2 == NULL) cur->next = p1;
if (p1 == NULL && p2 != NULL) cur->next = p2;