C++:将两个单链表合并成一个单链表

 

建立两个单链表L1,L2,并将其首位相连,合并成一个单链表L3

L1:x1,x2,x3,x4,...,xn;

L2:y1,y2,y3,y4,...,yn;

L3:x1,x2,x3,x4,...,xn,y1,y2,y3,...,yn;

#include<iostream>
# include<stdio.h>
# include<malloc.h>
using namespace std;
typedef struct Node
{
    int data;
    struct Node *next;
}List;
void Create_List(List *&L,int x)
{
    List *s,*r;
    L=(List *)malloc(sizeof(List));
    L->next=NULL;
    r=L;
    for(int i=0;i<x;i++)
    {
        s=(List *)malloc(sizeof(List));
        scanf("%d",&s->data);
        r->next=s;
        r=s;
    }
    r->next=NULL;
}
void Connect_List(List *&L,List *&Q,int m,int n)
{
    List *l=L;
    List *q=Q;
    for(int i=0;i<n;i++)
    {
        l=l->next;
    }
    l->next=q->next;
}
void Print(List *&L,int n)
{
    List *p=L->next;
    while (p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}
int main()
{
    List *L,*Q;
    L=(List *)malloc(sizeof(List));
    Q=(List *)malloc(sizeof(List));
    int n,m;
    cin>>n;
    Create_List(L,n);
    cin>>m;
    Create_List(Q,m);
    Connect_List(L,Q,m,n);
    Print(L,n);
    free(L);
    return 0;
}

Sample:

4

1 2 3 4

3

1 2 3

Output:

4

1 2 3 4

3

1 2 3

1 2 3 4 1 2 3

  • 21
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值