c++语言实现单链表的交并并输出并集
时间: 2023-05-17 21:07:52 浏览: 111
以下是 C 语言实现单链表的交并并输出并集的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int arr[], int n) {
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
void printList(Node *head) {
for (Node *p = head; p != NULL; p = p->next) {
printf("%d ", p->data);
}
printf("\n");
}
Node *listIntersection(Node *list1, Node *list2) {
Node *head = NULL, *tail = NULL;
for (Node *p1 = list1; p1 != NULL; p1 = p1->next) {
for (Node *p2 = list2; p2 != NULL; p2 = p2->next) {
if (p1->data == p2->data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = p1->data;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
break;
}
}
}
return head;
}
Node *listUnion(Node *list1, Node *list2) {
Node *head = NULL, *tail = NULL;
for (Node *p1 = list1; p1 != NULL; p1 = p1->next) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = p1->data;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
for (Node *p2 = list2; p2 != NULL; p2 = p2->next) {
int found = 0;
for (Node *p = head; p != NULL; p = p->next) {
if (p2->data == p->data) {
found = 1;
break;
}
}
if (!found) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = p2->data;
node->next = NULL;
tail->next = node;
tail = node;
}
}
return head;
}
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 4, 5, 6, 7};
Node *list1 = createList(arr1, 5);
Node *list2 = createList(arr2, 5);
Node *intersection = listIntersection(list1, list2);
Node *unionSet = listUnion(list1, list2);
printf("Intersection: ");
printList(intersection);
printf("Union: ");
printList(unionSet);
return 0;
}
```
希望这个代码能够帮助你实现单链表的交并并输出并集。
阅读全文