设计一个算法,求两个单链表表示的集合的交集,并将结果用一个新的单链表保存并返回,用c语言代码表示
时间: 2023-03-31 10:02:54 浏览: 103
以下是求两个单链表的交集并保存到新的单链表中的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA ? pA->next : headB;
pB = pB ? pB->next : headA;
}
return pA;
}
int main() {
// 构造两个单链表
struct ListNode *headA = (struct ListNode *) malloc(sizeof(struct ListNode));
headA->val = 1;
headA->next = (struct ListNode *) malloc(sizeof(struct ListNode));
headA->next->val = 2;
headA->next->next = (struct ListNode *) malloc(sizeof(struct ListNode));
headA->next->next->val = 3;
headA->next->next->next = NULL;
struct ListNode *headB = (struct ListNode *) malloc(sizeof(struct ListNode));
headB->val = 2;
headB->next = (struct ListNode *) malloc(sizeof(struct ListNode));
headB->next->val = 3;
headB->next->next = (struct ListNode *) malloc(sizeof(struct ListNode));
headB->next->next->val = 4;
headB->next->next->next = NULL;
// 求两个单链表的交集
struct ListNode *intersection = getIntersectionNode(headA, headB);
// 输出结果
printf("Intersection: ");
while (intersection) {
printf("%d ", intersection->val);
intersection = intersection->next;
}
printf("\n");
// 释放内存
free(headA->next->next);
free(headA->next);
free(headA);
free(headB->next->next);
free(headB->next);
free(headB);
return ;
}
```
阅读全文