/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode * newHead = nullptr;
ListNode * cur = nullptr;
//比较两个链表头结点,将最小者摘下放到新链表后面
//首先考虑两者至少有一个为空链表时的情况
if(pHead1 == nullptr) return pHead2;
if(pHead2 == nullptr) return pHead1;
//两个链表都不为空的情况
//让cur指向新链表的第一个结点,第一个结点接入到新链表过程和其他结点有区别
if(pHead1->val <= pHead2->val)
{
newHead = pHead1;
pHead1 = pHead1->next;
}else{
newHead = pHead2;
pHead2 = pHead2->next;
}
newHead->next = nullptr;
cur = newHead;
//遍历两个链表中,将所指元素中较小者续接到新链表后面
while( pHead1 != nullptr && pHead2 != nullptr)
{
if(pHead1->val <= pHead2->val)
{
cur->next = pHead1;
cur = cur->next;
pHead1 = pHead1->next;
cur->next =nullptr;
}else
{
cur->next = pHead2;
cur = cur->next;
pHead2 = pHead2->next;
cur->next =nullptr;
}
}
//有一个链表还没遍历完,将其剩余部分续到新链表后面
if(pHead1 != nullptr) cur->next = pHead1;
else if(pHead2 != nullptr) cur->next = pHead2;
return newHead;
}
};
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode * newHead = nullptr;
ListNode * cur = nullptr;
//比较两个链表头结点,将最小者摘下放到新链表后面
//首先考虑两者至少有一个为空链表时的情况
if(pHead1 == nullptr) return pHead2;
if(pHead2 == nullptr) return pHead1;
//两个链表都不为空的情况
//让cur指向新链表的第一个结点,第一个结点接入到新链表过程和其他结点有区别
if(pHead1->val <= pHead2->val)
{
newHead = pHead1;
pHead1 = pHead1->next;
}else{
newHead = pHead2;
pHead2 = pHead2->next;
}
newHead->next = nullptr;
cur = newHead;
//遍历两个链表中,将所指元素中较小者续接到新链表后面
while( pHead1 != nullptr && pHead2 != nullptr)
{
if(pHead1->val <= pHead2->val)
{
cur->next = pHead1;
cur = cur->next;
pHead1 = pHead1->next;
cur->next =nullptr;
}else
{
cur->next = pHead2;
cur = cur->next;
pHead2 = pHead2->next;
cur->next =nullptr;
}
}
//有一个链表还没遍历完,将其剩余部分续到新链表后面
if(pHead1 != nullptr) cur->next = pHead1;
else if(pHead2 != nullptr) cur->next = pHead2;
return newHead;
}
};