建立两个单链表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