题解 | #直接遍历——合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode *pre = new ListNode(0); //新链表的头节点
ListNode*p=pre;//新链表中连接下一个结点的指针
while (pHead1 != nullptr && pHead2 != nullptr) {
if(pHead1->val <= pHead2->val){
p->next = pHead1;
pHead1 = pHead1->next;
}else {
p->next = pHead2;
pHead2 = pHead2->next;
}
p = p->next;
}
if(pHead1 == nullptr) p->next = pHead2; //pHead1为空,那就将剩下的pHead2连接到p后面
else p->next = pHead1;
return pre->next;
}
};
CVTE公司福利 691人发布
查看15道真题和解析