【C语言题解】题目 1673: 数据结构-集合union

本文介绍了如何使用C语言实现数据结构中的集合union操作,包括创建链表、插入元素以及查找元素。通过主函数展示了如何合并两个集合并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:数据结构-集合union - C语言网 (dotcpp.com)

```
#include<stdio.h>
#include<malloc.h>
typedef struct Union{
	int data;
	struct Union* next;
}*node,Node;
//建立链表函数
node creat (int);
//取出L链表中的第i个元素
int GetElem (node, int);
//查找链表中的某元素
int LocateElem (node, int);
//将元素插入到链表的末尾
void ListInsert (node, int);
//输出链表
void output (node);
int main(){
	int a,b;//两个集合中元素的个数
	node head1,head2;//头节点 
	int e;
	while (scanf("%d",&a)!=EOF){
		int i;
		//建立头节点
		head1=(node)malloc(sizeof(Node));
		head2=(node)malloc(sizeof(Node));
		//创建两个集合
		head1=creat(a);
		scanf ("%d",&b);
		head2=creat(b);
		//输出两个集合
		output(head1);
		output(head2);
		for (i=1;i<=b;i++){
			//取出第二个集合中的第i个元素
			e=GetElem (head2, i);
			//查找第一个集合中是否存在该元素
			//若不存在,将该元素插入到集合中
			if (!LocateElem(head1,e))
				ListInsert(head1,e);
			//每一次都输出当前的集合
			output(head1);
		}
		printf("\n");
	}
	return 0;
}
node creat (int n){
	int i;
	node h,p,q;
	h=(node)malloc(sizeof(Node));
	h->next=NULL;
	q=h;
	for (i=0;i<n;i++){
		p=(node)malloc(sizeof(Node));
		scanf ("%d",&(*p).data);
		p->next=q->next;
		q->next=p;
		q=p; 
	}
	return h;
}
int GetElem (node L, int i){
	node temp0;
	temp0=L;
	for (int j=1;j<=i;j++){
		temp0=temp0->next;
	}
	return temp0->data;
}
int LocateElem (node L, int e){
	node temp=L;
	while (temp->next !=NULL){
		temp=temp->next;
		if (temp->data == e)
			return 1;
	}
	return 0;
}
void ListInsert (node L, int e){
	node temp=L,p;
	while (temp->next !=NULL){
		temp=temp->next;
	}
	p=(node)malloc(sizeof(Node));
	p->data=e;
	p->next=temp->next; 
	temp->next=p;
}

void output (node L){
	node temp=L;
	while (temp->next !=NULL){
		temp=temp->next;
		printf("%d ",temp->data);
	}
	printf("\n");
}
```

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值