两个有序链表的合并(新表不含重复元素)c语言
时间: 2024-10-03 16:03:28 浏览: 37
在C语言中,合并两个有序链表(新表中不含重复元素),可以采用迭代或递归的方式实现。这里提供一种常见的迭代算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* mergeSortedLists(Node* head1, Node* head2) {
Node* merged = NULL; // 新链表头节点
if (head1 == NULL) return head2; // 如果list1为空,直接返回list2
if (head2 == NULL) return head1; // 如果list2为空,直接返回list1
// 比较当前两个列表的首节点并选择较小的那个
if (head1->data <= head2->data) {
merged = head1; // 将较小的节点添加到新链表
head1 = head1->next;
} else {
merged = head2;
head2 = head2->next;
}
// 一直迭代,直到有一个链表为空
while (head1 != NULL && head2 != NULL) {
if (head1->data <= head2->data) {
merged->next = head1;
head1 = head1->next;
} else {
merged->next = head2;
head2 = head2->next;
}
merged = merged->next;
}
// 将剩余未遍历完的部分连接到新链表末尾
if (head1 != NULL) merged->next = head1;
else merged->next = head2;
return merged;
}
// 示例:创建链表节点
void createList(int* arr, int size) {
Node* temp = NULL;
for (int i = 0; i < size; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = temp;
temp = newNode;
}
}
// 打印链表
void printList(Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
int arr1[] = {1, 3, 5};
int arr2[] = {2, 4, 6};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
createList(arr1, n1);
createList(arr2, n2);
Node* head1 = arr1; // list1
Node* head2 = arr2; // list2
Node* result = mergeSortedLists(head1, head2);
printf("Merged sorted list: \n");
printList(result);
return 0;
}
```
在这个示例中,我们首先创建两个有序数组,并将其转换为链表结构。然后通过`mergeSortedLists`函数合并这两个链表,最后打印出合并后的结果。
阅读全文