C语言利用链表求集合的交集

Description

 假设元素依值递增有序排列的线性表A和B分别表示两个集合(即同一表中的元素值各不相同),现要求另辟空间构成一个线性表C,其元素为A和B中元素的交集,且表C中的元素也依值递增有序排列。

输入A和B集合中的元素;

输出A和B的交集C中的元素。

提示:存储结构采用带表头结点的循环单链表,结点结构如下:

typedef struct Node

{

    int data;  

    struct Node *next;

}LNode,*LinkList;

要求:

(1)编写函数按照升序序列输入元素值,建立集合的循环单链表。

(2) 编写函数实现集合的求交集算法。

(3)编写函数依次输出集合中的元素。

(4)编写main(),调用上述函数完成题目要求。

Input

 输入集合A的元素个数

按照升序依次输入集合A的元素值

输入集合B的元素个数

按照升序依次输入集合B的元素值

Output

 依次输出A和B的交集C中的元素。

Sample Input

5
10 20 30 40 50
6
5 16 20 35 40 80

Sample Output

20 40

 

#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int data;
    struct Node *next;
}LNode,*LinkList;
int length_C
  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是使用链表实现交集C语言代码示例: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构 struct Collection { char c; struct Collection* next; }; // 初始化集合链表 struct Collection* init(struct Collection* c) { c = (struct Collection*)malloc(sizeof(struct Collection)); c->next = NULL; return c; } // 将输入集合元素的字符串转换为链表 struct Collection* createinit(struct Collection* c, char z[], int n) { struct Collection* p = c; for (int i = 0; i < n; i++) { struct Collection* q = (struct Collection*)malloc(sizeof(struct Collection)); q->c = z[i]; p->next = q; p = q; } p->next = NULL; return c; } // 链表交集操作 struct Collection* intersection(struct Collection* c1, struct Collection* c2) { struct Collection* result = NULL; struct Collection* p = c1->next; while (p != NULL) { struct Collection* q = c2->next; while (q != NULL) { if (p->c == q->c) { struct Collection* newNode = (struct Collection*)malloc(sizeof(struct Collection)); newNode->c = p->c; newNode->next = result; result = newNode; break; } q = q->next; } p = p->next; } return result; } // 打印链表 void printList(struct Collection* c) { struct Collection* p = c; while (p != NULL) { printf("%c ", p->c); p = p->next; } printf("\n"); } int main() { struct Collection* c1 = NULL; struct Collection* c2 = NULL; struct Collection* result = NULL; // 初始化集合链表 c1 = init(c1); c2 = init(c2); // 将输入集合元素的字符串转换为链表 char z1[] = {'a', 'b', 'c', 'd'}; char z2[] = {'c', 'd', 'e', 'f'}; int n1 = sizeof(z1) / sizeof(z1[0]); int n2 = sizeof(z2) / sizeof(z2[0]); c1 = createinit(c1, z1, n1); c2 = createinit(c2, z2, n2); // 链表交集操作 result = intersection(c1, c2); // 打印结果 printf("Intersection: "); printList(result); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值