早教吧作业答案频道 -->其他-->
c语言给定两个集合A和B,求集合A和集合B的并集。给定两个集合A和B,求集合A和集合B的并集。例如:A={1,2,3},B={2,3,4},则A∪B={1,2,3,4}
题目详情
c语言 给定两个集合A和B,求集合A和集合B的并集。
给定两个集合A和B,求集合A和集合B的并集。
例如:A = {1,2,3},B = {2,3,4},则A∪B = {1,2,3,4}
给定两个集合A和B,求集合A和集合B的并集。
例如:A = {1,2,3},B = {2,3,4},则A∪B = {1,2,3,4}
▼优质解答
答案和解析
struct Link *Union(struct Link *head1, struct Link *head2)
{
struct Link *p1 = head1->next, *p2 = head2->next;
struct Link *head, *p, *q;
head = (struct Link *)malloc(sizeof(struct Link));
head->next = NULL;
p = head;
while ((p1 != NULL) && (p2 != NULL))
{
q = (struct Link*)malloc(sizeof(struct Link));
q->next = NULL;
if (p1->data == p2->data)
{
q->data = p1->data;
p1 = p1->next;
p2 = p2->next;
}
else if (p1->data < p2->data)
{
q->data = p1->data;
p1 = p1->next;
}
else
{
q->data = p2->data;
p2 = p2->next;
}
p->next = q;
p = q;
}
if(p1 != NULL){
while(p1 != NULL){
q = (struct* Link)malloc(sizeof(struct Link));
q->next = NULL;
q->data = p1->data;
p1 = p1->next;
p->next = q;
p = q;
}
}else if(p2 != NULL){
q = (struct* Link)malloc(sizeof(struct Link));
q->next = NULL;
q->data = p2->data;
p2 = p2->next;
p->next = q;
p = q;
}
return head;
}
//适用于p1,p2链表都没有重复data的情况
{
struct Link *p1 = head1->next, *p2 = head2->next;
struct Link *head, *p, *q;
head = (struct Link *)malloc(sizeof(struct Link));
head->next = NULL;
p = head;
while ((p1 != NULL) && (p2 != NULL))
{
q = (struct Link*)malloc(sizeof(struct Link));
q->next = NULL;
if (p1->data == p2->data)
{
q->data = p1->data;
p1 = p1->next;
p2 = p2->next;
}
else if (p1->data < p2->data)
{
q->data = p1->data;
p1 = p1->next;
}
else
{
q->data = p2->data;
p2 = p2->next;
}
p->next = q;
p = q;
}
if(p1 != NULL){
while(p1 != NULL){
q = (struct* Link)malloc(sizeof(struct Link));
q->next = NULL;
q->data = p1->data;
p1 = p1->next;
p->next = q;
p = q;
}
}else if(p2 != NULL){
q = (struct* Link)malloc(sizeof(struct Link));
q->next = NULL;
q->data = p2->data;
p2 = p2->next;
p->next = q;
p = q;
}
return head;
}
//适用于p1,p2链表都没有重复data的情况
看了 c语言给定两个集合A和B,求...的网友还看了以下:
包含关系{a}含于A与属于关系a∈A有什么区别?有人说是包含关系指的是集合之间的关系,例如集合A= 2020-04-05 …
若全集U={1,2,3,4,5,6},M={2,3},N={1,4},则集合N∩(CuM)等于( 2020-04-05 …
一、定义A与B的差集A-B={x|x∈A且x不属于B}.(1)设全集为U,请用集合的交、并、补运算 2020-04-06 …
沥青混凝土面层集料的最大粒径宜从上到下逐渐().上面层沥青混合料的最大粒径不宜超过层厚的()A.减 2020-04-07 …
集合A={1,2,-3}B={-1,-2,3,4}从A、B中取一个元素P(x,y)的坐标,位于第一 2020-05-14 …
设全集I={0,1,2,3},集合M={0,1,2},N={0,2,3},则集合MUC1U=?A. 2020-05-16 …
1.已知非空集合P满足(1)P包含于{1,2,3,4,5}(2)a∈P,则6-a∈P.那么,符合上 2020-05-21 …
两个集合可以互为真子集吗?比如集合A={1,2,3},集合B={2,3,4},它们有相同的元素也有 2020-07-08 …
带有a的参数的不等式集合题.脑晕.已知不等式x^2-3(a+1)x+6a+2≤0的解集为A,x^2 2020-07-12 …
空集是任何集合的子数.那么算并集的时候为什么不算上空集啊A={1,2,3}B={1,2,3,4,5 2020-07-13 …