题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
#include <list>
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if(pHead1==nullptr) return pHead2;
if(pHead2==nullptr) return pHead1;
if(pHead1->val<pHead2->val)
{
pHead1->next=Merge(pHead1->next,pHead2);
return pHead1;
}
else{
pHead2->next=Merge(pHead2->next,pHead1);
return pHead2;
}
};
};
首先判断特殊情况,某一个为空链表的情况,当然这包括了两者均为空链表的情况。
当phead1的结点值小于phead2的结点值时,将phead1作为新生成链表的头结点,合并phead1剩余链表部分和phead2。
当phead2的结点值小于phead1的结点值时同理。