参考代码:
#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 人评分
C语言程序设计教程(第三版)课后习题10.2 (C语言代码)浏览:673 |
C语言程序设计教程(第三版)课后习题6.3 (C语言代码)浏览:435 |
蛇行矩阵 (C语言代码)浏览:752 |
a+b浏览:433 |
1113题解浏览:789 |
字符逆序 (C语言代码)浏览:620 |
C语言程序设计教程(第三版)课后习题6.8 (C语言代码)浏览:617 |
排序算法(选择,插入,冒泡)浏览:775 |
C语言程序设计教程(第三版)课后习题11.5 (C语言代码)浏览:999 |
小O的图案 (C语言代码)浏览:915 |