集合交差并三種操作的C實(shí)現(xiàn)
/*********************************************
集合的差集操作
參數(shù): 兩個(gè)集合的指針
返回值: 新的集合指針
*********************************************/
Set * XorSets(const Set *s1, const Set *s2)
{
Set *newset = NULL;
Node_t *head = NULL;
assert(s1 != NULL && s2 != NULL);
if(s1->head == NULL)
{
/*空集合*/
creat_nullset(&newset);
return newset;
}
if(s2->head == NULL)
{
copySet(&newset,s1);
return newset;
}
/*newset和s1是相同的*/
copySet(&newset,s1);
head = s1->head;
while(head != NULL)
{
/*如果s2中存在當(dāng)前元素,刪除*/
if(findElement(s2, head->value))
{
delete_setElement(&newset,head->value);
}
head = head->next;
}
return newset;
}
集合打印操作、集合的刪除操作
/*********************************************
打印集合
參數(shù): 集合指針
返回: void
**********************************************/
void print_set(const Set *s)
{
Node_t * head = NULL;
int i = 0;
assert(s);
head = s->head;
printf("{ ");
while(head != NULL)
{
++i;
printf("%d ",head->value);
if(i % 5 == 0 && i != 0)
{
i = 0;
// printf("");
}
head = head->next;
}
printf("}");
}
/*********************************************
刪除一個(gè)集合
參數(shù): 指向集合指針的指針
返回值: void
**********************************************/
void delete_set(Set **s)
{
Node_t *head = NULL;
Node_t *temp = NULL;
// assert(*s);
if(*s == NULL)
return;
head = (*s)->head;
while(head != NULL)
{
temp = head;
head = head->next;
free(temp);
(*s)->size --;
temp = NULL;
}
free(*s);
*s = NULL;
}
最后是我的測(cè)試程序:
/************************************************
主函數(shù)
完成各個(gè)函數(shù)的測(cè)試工作
最后需要完成內(nèi)存的釋放
************************************************/
int main()
{
Set* sets1 = NULL;
Set* sets2 = NULL;
Set* sets3 = NULL;
Set* sets4 = NULL;
int i = 0;
int j = 0;
for(i = 0; i < 10; ++ i)
{
if(!create_set(&sets1, i+10))
break;
j = i + 10 - 5;
if(!create_set(&sets2, j))
break;
}
printf("Set1 : ");
print_set(sets1);
printf("Set2 : ");
print_set(sets2);
sets3 = OrSets(sets1,sets2);
printf("Set1 + Set2: ");
print_set(sets3);
sets3 = OrSets(sets2,sets1);
printf("Set2 + Set1: ");
print_set(sets3);
delete_set(&sets3);
sets3 = AndSets(sets1,sets2);
printf("Set1 * Set2: ");
print_set(sets3);
delete_set(&sets3);
sets3 = AndSets(sets2,sets1);
printf("Set2 * Set1: ");
print_set(sets3);
delete_set(&sets3);
sets3 = XorSets(sets1,sets2);
printf("Set1 - Set2: ");
print_set(sets3);
delete_set(&sets3);
// creat_nullset(&sets4);
sets3 = XorSets(sets2,sets1);
printf("Set2 - Set1: ");
print_set(sets3);
delete_set(&sets1);
delete_set(&sets2);
delete_set(&sets3);
delete_set(&sets4);
return 0;
}
實(shí)驗(yàn)效果:
總結(jié):
該實(shí)現(xiàn)并沒(méi)有考慮性能方面,基本上實(shí)現(xiàn)了集合的簡(jiǎn)單操作。后面有時(shí)間再想想如何優(yōu)化查找和刪除操作。
評(píng)論