C语言,链表实现并集
时间: 2024-02-02 11:04:56 浏览: 39
以下是使用C语言实现链表并集的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 插入节点到链表尾部
void insert(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 合并两个有序链表
struct Node* mergeLists(struct Node* list1, struct Node* list2) {
struct Node* result = NULL;
struct Node* current = NULL;
while (list1 != NULL && list2 != NULL) {
if (list1->data < list2->data) {
if (result == NULL) {
result = current = list1;
} else {
current->next = list1;
current = current->next;
}
list1 = list1->next;
} else {
if (result == NULL) {
result = current = list2;
} else {
current->next = list2;
current = current->next;
}
list2 = list2->next;
}
}
if (list1 != NULL) {
if (result == NULL) {
result = list1;
} else {
current->next = list1;
}
}
if (list2 != NULL) {
if (result == NULL) {
result = list2;
} else {
current->next = list2;
}
}
return result;
}
int main() {
// 创建链表1: 1->2->3
struct Node* list1 = NULL;
insert(&list1, 1);
insert(&list1, 2);
insert(&list1, 3);
// 创建链表2: 2->3->5
struct Node* list2 = NULL;
insert(&list2, 2);
insert(&list2, 3);
insert(&list2, 5);
// 合并链表并打印结果
struct Node* mergedList = mergeLists(list1, list2);
printList(mergedList);
return 0;
}
```