永发信息网

两个单链表合并如何做?

答案:3  悬赏:0  手机版
解决时间 2021-02-02 20:07
  • 提问者网友:孤山下
  • 2021-02-02 14:35
两个单链表合并如何做?
最佳答案
  • 五星知识达人网友:零点过十分
  • 2021-02-02 15:25
#include
#include
#include
#define LEN sizeof(struct student)
struct student
{
int num;
char name[50];
struct student *next;
struct student *ptr;
};
int n;
struct student *creat()
{
struct student *head;
struct student *p1,*p2;
int i;
n=0;
p1=p2=(struct student *)malloc(LEN);
printf("please input mum/name \n");
scanf("%d %s",&p1->num,p1->name);
head=NULL;
while(p1->num)
{
n++;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
printf("please input mum/name \n");
scanf("%d %s",&p1->num,p1->name);
}
p2->next=NULL;
p1=head;
for(i=0;i {
p1->ptr=NULL;
p1=p1->next;
}
return head;}
struct student *hebing(struct student *head1,struct student *head2)
{
struct student *p1;
struct student *p2;
int i;
p1=head1;
p2=head2;
for(i=0;i {
p1->ptr=p2;
p1=p1->next;
p2=p2->next;
}
p1=head1;
p2=head2;
for(i=0;i {
p2->ptr=p1->next;
p1=p1->next;
p2=p2->next;
}
return head1;
}
int main(void)
{
struct student *head1;
struct student *head2;
struct student *head3;
int i;
head1=creat();
n=0;
head2=creat();
head3=hebing(head1,head2);
for(i=0;i<2*n;i++)
{

printf("%d %s\n",head3->num,head3->name);
head3=head3->ptr;
}
return 0;
}
全部回答
  • 1楼网友:时间的尘埃
  • 2021-02-02 16:25
把其中一个的末节点指向下一个的头节点不可以么?
  • 2楼网友:毛毛
  • 2021-02-02 16:10
#include "stdio.h"
#include "stdlib.h"
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
void ListInit(LinkList *L)
{
*L=(LinkList)malloc(sizeof(LNode));
(*L)->next=NULL;
}
void EndInsert(LinkList L,ElemType e)
{
LinkList p=L;
while(p->next)
p=p->next;
p->next=(LinkList)malloc(sizeof(LNode));
p->next->data=e;
p->next->next=NULL;
}
void ListTraverse(LinkList L)
{
LinkList p=L->next;
while(p)
{
printf("->%d",p->data);
p=p->next;
}
}
void Merge(LinkList LA,LinkList *LB,LinkList *LC)
{
LinkList pa,pb,pc;
pa=LA->next;pb=(*LB)->next;pc=(*LC)=LA;
while(pa&&pb)
{
pc->next=pa;
pc=pa;
pa=pa->next;
pc->next=pb;
pc=pb;
pb=pb->next;
}
pc->next=pa?pa:pb;
free(*LB);
LB=NULL;
}
void main()
{
int i;
LinkList LA,LB,LC;
ListInit(&LA);
ListInit(&LB);
ListInit(&LC);
for(i=1;i<10;i++)
EndInsert(LA,i);
for(i=5;i<20;i++)
EndInsert(LB,i);
Merge(LA,&LB,&LC);
ListTraverse(LC);
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯