题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

​https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking​

题解:

class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode *p = new ListNode(0);
ListNode *res = p;
while (pHead1 != NULL && pHead2 != NULL) {
if (pHead1->val < pHead2->val) {
p->next = new ListNode(pHead1->val);
p = p->next;
pHead1 = pHead1->next;
}
else {
p->next = new ListNode(pHead2->val);
p = p->next;
pHead2 = pHead2->next;
}
}
while (pHead1 != NULL) {
p->next = new ListNode(pHead1->val);
p = p->next;
pHead1 = pHead1->next;
}
while (pHead2 != NULL) {
p->next = new ListNode(pHead2->val);
p = p->next;
pHead2 = pHead2->next;
}
return res->next;
}
};