早教吧 育儿知识 作业答案 考试题库 百科 知识分享

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}
▼优质解答
答案和解析
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的情况