实验数据结构(保存了两日内书面实验报告) 列表中的整合
huangjing
列表中的整合,要求O(la*lb)复杂性。实际插入是什么。需要注意的是,在特殊情况下的列表的开始和结束的假设
代码
#include<cstdio>
#include<cstring>
#include<cstdlib>
typedef struct node
{
int data;
struct node *next;
}Node,*listnode;
int lena,lenb;
void creatlist(listnode &head,int flag)
{
int x=1;
listnode p,xx;
head->next=NULL;
xx=head;
while(x!=0)
{
p=(listnode)malloc(sizeof(struct node));
scanf("%d",&x);
if(x==0) break;
if(flag)
lena++;
else
lenb++;
p->data=x;
p->next=NULL;
xx->next=p;
xx=p;
}
}//创建链表
void forlist(listnode &head)
{
listnode p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}//遍历链表
void Insert(listnode &la,int val)
{
listnode p,last,cur;
p=la->next;
last=p;
cur=(listnode)malloc(sizeof(node));
cur->data=val;
if(p->data>val)
{
cur->next=p;
la->next=cur;
return;
}
while(p->data<val)
{
last=p;
p=p->next;
if(p==NULL) break;
}
cur->next=p;
last->next=cur;
}
void unionlist(listnode &la,listnode &lb)
{
int flag;
listnode xx,yy;
yy=lb->next;
for(int i=1;i<=lenb;i++)
{
flag=0;
int key=yy->data;
yy=yy->next;
xx=la->next;
for(int j=1;j<=lena;j++)
{
if(xx->data==key)
{
flag=1;
break;
}
else
xx=xx->next;
}
if(!flag)
{
Insert(la,key);
lena++;
}
}
}//合并链表
int main()
{
lena=lenb=0;
listnode heada,headb;
heada=(listnode)malloc(sizeof(struct node));
headb=(listnode)malloc(sizeof(struct node));
creatlist(heada,1);
creatlist(headb,0);
printf("链表la长度 lb长度:%d %d\n",lena,lenb);
printf("链表ha为");
forlist(heada);
printf("\n");
printf("链表hb为");
forlist(headb);
printf("\n");
unionlist(heada,headb);
printf("合并后的链表:\n");
forlist(heada);
printf("\n");
forlist(headb);
return 0;
}
/*
3 4 6 18 0
2 3 5 6 7 19 20 0
*/
版权声明:本文博客原创文章,博客,未经同意,不得转载。
浙公网安备 33010602011771号