剑指offer面试题17合并两个有序的单链表之后还有序(递归)

#include<iostream>
#include<cstdio>
using namespace std;

struct Node
{
    int data;
    Node * next;
};

void PrintList(Node * head)
{
    if(head==NULL)
    printf("empty List\n");
    Node * p=head;
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    cout<<endl;
}
/*
这个递归函数还是比较好想的。 参数是两个链表当前要合并的指针
所以初始时都是头指针,然后定义一个newhead 这个newhead就是两个当前指针中 data小的的指针
并且把这个newhewad返回给之前调用的那个函数的next 这样就连起来了
*/
Node * MergeSortedList(Node * p1,Node *p2)
{
    if(p1==NULL) return p2;
    if(p2==NULL) return p1;
    Node * newhead=NULL;
    if(p1->data<p2->data)
    {
        newhead=p1;
        newhead->next=MergeSortedList(p1->next,p2);
    }
    else
    {
        newhead=p2;
        newhead->next=MergeSortedList(p1,p2->next);
    }
    return newhead;
}


int main()
{
    //freopen("/home/gl/in","r",stdin);
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        Node * head1;
        if(!n)
        head1=NULL;
        else
        head1=new Node();
        Node * p=head1;
        for(int i=0;i<n;++i)
        {
            scanf("%d",&p->data);
            if(i==n-1)
            {
                p->next=NULL;
                break;
            }
            p->next=new Node();
            p=p->next;
        }
        PrintList(head1);

        scanf("%d",&n);
        Node * head2;
        if(!n)
        head2=NULL;
        else
        head2=new Node();
        p=head2;
        for(int i=0;i<n;++i)
        {
            scanf("%d",&p->data);
            if(i==n-1)
            {
                p->next=NULL;
                break;
            }
            p->next=new Node();
            p=p->next;
        }
        PrintList(head2);
        Node * newhead=MergeSortedList(head1,head2);
        PrintList(newhead);
        cout<<endl<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值