1. 數據結構 用c語言寫的 集合的並、交和差運算的程序
可以用二個一維數組,
再用兩個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...!
2. 如何利用c語言實現集合的運算
這種集合問題,一般是使用鏈表來處理。
比如說有兩個鏈表list1,list2,它們分別用來存儲集合A,B
如果要對A,B進行並運算,
那麼可以首先定義一個新的鏈表list3,然後讓list1和list2的值進行循環的比較,如果有相同的值,那麼就將這個值放入list3中,直到沒有相同的值為止。
大致的演算法就是這樣了。
3. C語言求集合運算
可以用線性表模擬集合,把兩個線性表中一樣的數提取出來就是交集,所有元素組成的就是並集,還可以用C++重載運算符實現+就求並集之類的。
4. 用C語言編寫一個集合的交,並和差運算的程序怎麼寫啊
/*第一,你的題意不明,我只能輸入兩個集合了【互異性由輸入保證】*/
#include<stdio.h>
#include<string.h>
void main()
{
char temp[60]="",str1[30]="",str2[30]="",i,j,l1,l2,ch;
printf("STR1:");
gets(str1);
printf("STR2:");
gets(str2);
l1=strlen(str1);
l2=strlen(str2);
//交集
printf(" 交集: {");
for(i=0;i<l1;i++)
for(j=0;j<l2;j++)
if(str1[i]==str2[j]) printf("%c,",str1[i]);
printf("} ");
//並集 偷懶的演算法: 合並->排序->刪除相同
printf(" 並集: {");
/*合並*/sprintf(temp,"%s%s",str1,str2);
/*排序*/
for(i=0;i<l1+l2-1;i++)
for(j=i+1;j<l1+l2;j++)
if(temp[i]>temp[j])
{
char ch;
ch=temp[i];
temp[i]=temp[j];
temp[j]=ch;
}
/*刪除相同字元*/
for(i=j=1;i<l1+l2;i++)
if(temp[i]!=temp[j-1]) temp[j++]=temp[i];
temp[j]='