求助一交替合并链表问题
设线性表LA=(a1, a2, …, am),LB=(b1, b2, …, bn)。试编写一个算法,将LA、LB合并为线性表LC,使LC=(a1,b1...am,bm,bm+1...bn) m<=n时
或者LC=(a1,b1...an,bn,an+1...am) m>n时
要求LA、LB和LC均以单链表为存储结构,且LC表利用LA和LB中结点空间,这里m和n的值没有保存在头结点中。
程序代码:#include<stdio.h>
#include<malloc.h>
struct linknode
{
int data;
struct linknode *next;
};
struct linknode *create()//创建单链表
{
int d;
int i=1;
struct linknode *head,*s,*t;
head=NULL;
printf("建立一个单链表,data域数据已0结束:\n");
while(1)
{
printf("%d:",i);
scanf("%d",&d);
if(d==0)
break;
if(i==1)//建立第一个结点
{
head=(struct linknode *)malloc(sizeof(struct linknode));
head->data=d;
head->next=NULL;
t=head;
}
else//建立其余结点
{
s=(struct linknode *)malloc(sizeof(struct linknode));
s->data=d;
s->next=NULL;
t->next=s;
t=s;
}
i++;
}
return head;
}
void disp(struct linknode *head)//输出结点数据
{
struct linknode *p=head;
printf("输出一个单链表:\n");
if(p==NULL)
printf("空");
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
}
int len(struct linknode *head)//返回单链表的长度
{
int pcount=0;//结点计数器
struct linknode *p=head;
while(p!=NULL)
{
p=p->next;
pcount++;
}
return pcount;
}
struct linknode *JCHB(struct linknode *heada,struct linknode *headb)//交叉合并函数
{
struct linknode *ha,*hb,*t,*s,*hc;
hc=heada;
ha=heada;
t=heada;
hb=headb;
s=headb;
if(len(ha)!=len(hb))
{
printf("不合题意,链表长度不同\n");
return NULL;
}
while(ha!=NULL)
{
t=ha;
ha=ha->next;
t->next=hb;
s=hb;
hb=hb->next;
s->next=ha;
}
return (hc);
}
void main()
{
struct linknode *heada,*headb,*headc;
heada=create();
disp(heada);//输出链表数据
headb=create();
disp(headb);
headc=JCHB(heada,headb);
disp(headc);
}这是我以前做的,不过要求是链表长度一样。不过整体思路都是一样的,楼主参考一下哈