//迭代
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode *vhead = new ListNode(-1);
ListNode *cur = vhead;
while (pHead1 && pHead2) {
if (pHead1->val <= pHead2->val) {
cur->next = pHead1;
pHead1 = pHead1->next;
}
else {
cur->next = pHead2;
pHead2 = pHead2->next;
}
cur = cur->next;
}
cur->next = pHead1 ? pHead1 : pHead2;
return vhead->next;
}
};
/*
递归
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;
}
else if(pHead2== NULL){
return pHead1;
}
struct ListNode* tem = NULL;
if(pHead1->val < pHead2->val)
{
tem= pHead1;
// phead1后续节点和pHead2节点继续递归
tem->next = Merge(pHead1->next, pHead2);
}
else
{
tem = pHead2;
tem->next = Merge(pHead1, pHead2->next);
}
return tem;
}
};
剑指数据结构-合并两个有序链表
最新推荐文章于 2022-11-27 17:08:17 发布