剑指offer之合并两个排序的链表
作者:互联网
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
示例1
输入
{1,3,5},{2,4,6}
返回值
{1,2,3,4,5,6}
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL) return pHead2;
if(pHead2==NULL) return pHead1;
ListNode* rt = NULL;
ListNode* cur = NULL;
ListNode* pre = NULL;
if(pHead1->val < pHead2->val)
{
rt = pHead1;
}
else
{
rt = pHead2;
}
while(pHead1 != NULL && pHead2 != NULL)
{
if(pHead1->val < pHead2->val)
{
cur = pHead1;
pHead1 = pHead1->next;
}
else
{
cur = pHead2;
pHead2 = pHead2->next;
}
if(pre != NULL)
{
pre->next = cur;
}
pre = cur;
}
if(pHead1 == NULL)
{
cur->next = pHead2;
}
if(pHead2 == NULL)
{
cur->next = pHead1;
}
return rt;
}
};
标签:NULL,ListNode,cur,offer,next,链表,pHead1,pHead2,排序 来源: https://blog.csdn.net/A18373279153/article/details/113814595