C语言,链表实现交集
时间: 2024-02-02 20:04:56 浏览: 30
以下是使用链表实现交集的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;
}
```