参考代码:
#include <stdlib.h>
#include<stdio.h>
#include<ctype.h>
#include<string.h>
typedef struct listt//定义结构体
{
int data;
struct listt *next;
}*lists,List;//取别名
lists creatlist(int a)//创建链表
{
lists node;//定义头结点
node = (lists)malloc(sizeof(List));//取头结点
node->next=NULL;
lists w;
lists q;
w = node;
while(a--)
{
q = (lists)malloc(sizeof(List));
scanf("%d",&(*q).data);
q->next = w->next;
w->next = q;
w = q;
}
return(node);
}
int Listlength(lists a)//计算链表的长度
{
int len = 0;
a = a->next;
while(a!=NULL)
{
a = a->next;
len++;
}
return len;
}
int GetElem(lists x,int i,int e)//取第i个元素给e
{
lists w;
w = x;
w = w->next;//把头结点去掉
while(i--)
{
e = w->data;
w = w->next;
}
return e;
}
int LocateElem(lists l,int e)//判断l中是否有元素和e相等
{
lists w;
w = l;
w = w->next;
int len = Listlength(l);
for(int i = 0;i < len;i++)
{
if(w->data==e)
{
return 1;
}
w = w->next;
}
return 0;
}
void ListInsert(lists a,int e)
{
lists w;
w = a;
w=w->next;
int len = Listlength(w);
while(len--)
{
w=w->next;
}
lists p;
p = (lists)malloc(sizeof(List));
p->data = e;
p->next=NULL;
w->next = p;
}
void display(lists f)//将链表展示出来
{
lists c;
c = f;
c = c->next;
while(c!=NULL)
{
printf("%d ",c->data);
c = c->next;
}
printf("\n");
}
void outList(lists a)//释放结点
{
lists c;
a = a->next;
while(a!=NULL)
{
c = a;
a = a->next;
free(c);
}
}
void Union(lists a,lists b)
{
int lena = 0;
int lenb = 0;
int e;
int f;
lena = Listlength(a);
display(a);
display(b);
lenb = Listlength(b);
for(int i = 1;i <= lenb;i++)
{
f = GetElem(b,i,e);
if(LocateElem(a,f)==0)//判断是否含有不同元素,如果没有就进行插入
{
ListInsert(a,f);
}
display(a);//每次循环打印出一次
}
printf("\n");
outList(a);
}
int main()
{
int n;
int m;
lists a,b;
while(scanf("%d",&n)!=EOF)
{
a = creatlist(n);
scanf("%d",&m);
b = creatlist(m);
Union(a,b);
}
return 0;
}
0.0分
2 人评分
2003年秋浙江省计算机等级考试二级C 编程题(1) (C语言代码)浏览:677 |
【绝对值排序】 (C语言代码)浏览:713 |
字符串对比 (C语言代码)浏览:1398 |
C语言程序设计教程(第三版)课后习题10.7 (C语言代码)浏览:538 |
C语言程序设计教程(第三版)课后习题8.1 (C语言代码)浏览:517 |
【偶数求和】 (C语言代码)浏览:556 |
用筛法求之N内的素数。 (C语言代码)浏览:646 |
【求[X,Y]内被除3余1并且被除5余3的整数的和】 (C语言代码)浏览:672 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:460 |
C语言训练-自由落体问题 (C语言代码)浏览:610 |