用数据结构的内容用c++写俩个单链表并集
时间: 2023-05-15 12:07:18 浏览: 64
以下是用 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;
Node* 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 = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
Node* mergeLists(Node* list1, Node* list2) {
Node* head = NULL;
Node* tail = NULL;
while (list1 != NULL && list2 != NULL) {
if (list1->data < list2->data) {
if (head == NULL) {
head = list1;
tail = list1;
} else {
tail->next = list1;
tail = list1;
}
list1 = list1->next;
} else if (list1->data > list2->data) {
if (head == NULL) {
head = list2;
tail = list2;
} else {
tail->next = list2;
tail = list2;
}
list2 = list2->next;
} else {
if (head == NULL) {
head = list1;
tail = list1;
} else {
tail->next = list1;
tail = list1;
}
list1 = list1->next;
list2 = list2->next;
}
}
if (list1 != NULL) {
if (head == NULL) {
head = list1;
} else {
tail->next = list1;
}
}
if (list2 != NULL) {
if (head == NULL) {
head = list2;
} else {
tail->next = list2;
}
}
return head;
}
int main() {
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 4, 6, 8};
Node* list1 = createList(arr1, 4);
Node* list2 = createList(arr2, 4);
Node* mergedList = mergeLists(list1, list2);
printList(mergedList);
return 0;
}
```
输出结果为:1 2 3 4 5 6 7 8