16:合并两个排序的链表
2019-08-06 本文已影响0人
iwtbam
题目描述
- 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
- 无
AC代码
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (!pHead1)
return pHead2;
if (!pHead2)
return pHead1;
ListNode* temp1 = pHead1->val < pHead2->val? pHead1 : pHead2;
ListNode* temp2 = pHead1->val < pHead2->val? pHead2 : pHead1;
ListNode* nHead = temp1;
ListNode* pre = temp1;
while (temp2) {
while (temp1&&temp2->val >= temp1->val) {
pre = temp1;
temp1 = temp1->next;
}
if (temp1) {
pre->next = temp2;
ListNode* temp22 = temp2->next;
temp2->next = temp1;
pre = temp2;
temp2 = temp22;
}
else{
pre->next = temp2;
return nHead;
}
}
return nHead;
}
};