再用两个for循环来判断结果:交,并,差
在for循环中,用一个if来判断一下,是不是a[0]==b[j],只要有相等的,就令之放在c[0]
这就是交集!!
并集就好求吧,
只要令c[i]=a[i],再来一个就是c[i+j+1]=b[j](因祥姿为我这里是考虑j=0开始的,然后自加差贺敏就是在交上改动一下就可以了,只要是a[0]!=b[j],就把它放到c[]这个数组里面去~!!!!
1:并集的程序。
求集合LA和禅宴枝集合LB的并集
#define NULL 0
struct JD
{ int data
struct JD *next
}
int find(int number,struct JD *h)
{ while(h->data)
{ if(h->data!=number)
{ h=h->next
continue
}
else
return 0
}
return 1
}
struct JD * make()
{ struct JD *h=NULL,*p=NULL
int number,tf
h=(struct JD *)malloc(sizeof(struct JD))
scanf("%d",&h->data)
p=h
while(p->data)
{ p->next=(struct JD *)malloc(sizeof(struct JD))
p=p->next
p->data=0
scanf("%d",&number)
tf=find(number,h)
if(tf)
p->data=number
else
continue
}
return h
}
void print(struct JD *h)
{ while(h->data)
{ printf("%d ",h->data)
h=h->next
}
}
struct JD * change(struct JD *la,struct JD *lb)
{ struct JD *h,*p,*s,*q
int number,tf
p=lb
while(p->data)
{ number=p->data
tf=find(number,la)
p=p->next
if(tf)
{ s=(struct JD *)malloc(sizeof(struct JD))
s->data=number
s->next=la
la=s
}
else
continue
}
return la
}
void del(struct JD *h)
{ struct JD *p=h->next
while(h->data)
{ free(h)
h=p
p=p->next
}
free(h)
}
main()
{ struct JD *la,*lb
printf("\n\nGive the number to LA :\n\n")
la=make()
printf("\nLA is: ")
print(la)
printf("\n\nGive the number to LB :\n\n")
lb=make()
printf("\nLB is: ")
print(lb)
la=change(la,lb)
printf("\n\n\nThe new LA=LA||LB is: ")
print(la)
del(la)
del(lb)
printf("\n\n\nPass any key to exit...!\n")
getch()
}
********** 程序运行结果 **********
Give the number to LA :
1↓
2↓
3↓
5↓
0↓
LA is: 1 2 3 5
Give the number to LB :
6↓
7↓
3↓
2↓
9↓
0↓
LB is: 6 7 3 2 9
The new LA=LA||LB is: 9 7 6 1 2 3 5
--------------------------------------------------
Pass any key to exit...!
#include <stdio.h>#include <stdlib.h>
#include <iostream>
using namespace std
//交集
void Intersection(int a[], int b[], int m, int n)
{
cout<<"两集合交集:"
for(int i = 0i <mi++)
{
for(int j = 0j <nj++)
{
if(a[i] == b[j])
{
cout<<a[i]<<' '
break
}
}
}
cout<<endl
}
//并集
void AddSets(int a[], int b[], int m, int n)
{
int flag
cout<<"两集合并集:"
for(int i = 0i <mi++)
{
flag = true
for(int j = 0j <nj++)
{
if(a[i] == b[j])
{
flag = false
break
}
}
if(flag) cout<<a[i]<<' '
}
for(int j = 0j <塌姿 nj++)
{
cout<<b[j]<<' '
}
cout<<endl
}
//差集
void SubSets(int a[], int b[], int m, int n)
{
int flag
cout<<"两集合差集:"
for(int i = 0i <mi++)
{
flag = true
for(int j = 0j <nj++)
{
if(a[i] == b[j])
{
flag = false
break
}
}
if(flag) cout<<a[i]<<' '
}
cout<<endl
}
void main()
{
int n1
int n2
int a[100]
int b[100]
cout<<"请输入第一个数组大小:"
cin>>n1
cout<<"请输入第一个数组元素:"
for (int i = 0i <n1i++)
{
cin>>a[i]
}
cout<<"请输氏衫凳入第二个数组大小:"
cin>>n2
cout<<"请输歼旅入第二个数组元素:"
for (i = 0i <n2i++)
{
cin>>b[i]
}
Intersection(a, b, n1, n2)
AddSets(a, b, n1, n2)
SubSets(a, b, n1, n2)
getchar()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)