剑指offer-合并两个有序链表(C++递归+指针法)

合并两个有序链表

输入两个单调递增的有序链表,输出两个链表合并后的链表,当然合成后的链表满足单调非递减规则

题解:
1)指针法:对链表中的元素,用对两个链表设置两个指针,对有序链表的数据逐个进行比较,较小的数据插入到合并的链表之中。

代码如下:

/*
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)
            return pHead2;
        if(!pHead2)
            return pHead1;
        ListNode *p;
        ListNode *List;
        if(pHead1->val<pHead2->val){
            List=pHead1;pHead1=pHead1->next;
        }
        else{
            List=pHead2;pHead2=pHead2->next;
        }
        p=List;
        while(pHead1&&pHead2){
            if(pHead1->val<pHead2->val){
                p->next=pHead1;
                p=p->next;
                pHead1=pHead1->next;
            }
            else{
                p->next=pHead2;
                p=p->next;
                pHead2=pHead2->next;
            }
        }
        while(pHead1){
            p->next=pHead1;
            p=p->next;
            pHead1=pHead1->next;
        }
        while(pHead2){
            p->next=pHead2;
            p=p->next;
            pHead2=pHead2->next;
        }
        return List;
    }
};

2)递归法:比较两个链表的头指针,将数据较小的数据接在合并链表后,然后将链表递归重新看作两个链表的合并。
即递归的每一次,便将两个链表中,较小的头节点合并进合并链表之中。
代码如下:

/*
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)
            return pHead2;
        if(!pHead2)
            return pHead1;
        ListNode *List;
        if(pHead1->val<pHead2->val){
            List=pHead1;
            List->next=Merge(pHead1->next,pHead2);
        }
        else{
            List=pHead2;
            List->next=Merge(pHead1,pHead2->next);
        }
        return List;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值