用c语言写一个合并两个有序链表的函数
时间: 2024-05-03 14:23:32 浏览: 12
以下是合并两个有序链表的C语言函数示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建新节点
struct ListNode* newNode(int val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 合并两个有序链表
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
// 创建一个虚拟头节点,并将其赋值为0
struct ListNode dummyHead = {0};
struct ListNode* tail = &dummyHead;
// 循环比较两个链表的节点值,将值小的节点接在尾部
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
// 将剩余的节点接在尾部
if (l1) {
tail->next = l1;
} else {
tail->next = l2;
}
// 返回虚拟头节点的下一个节点
return dummyHead.next;
}
// 打印链表
void printList(struct ListNode* head) {
while (head) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
// 创建两个有序链表
struct ListNode* l1 = newNode(1);
l1->next = newNode(3);
l1->next->next = newNode(5);
l1->next->next->next = newNode(7);
struct ListNode* l2 = newNode(2);
l2->next = newNode(4);
l2->next->next = newNode(6);
l2->next->next->next = newNode(8);
// 打印原始链表
printf("List 1: ");
printList(l1);
printf("List 2: ");
printList(l2);
// 合并两个有序链表
struct ListNode* newList = mergeTwoLists(l1, l2);
// 打印合并后的链表
printf("Merged List: ");
printList(newList);
return 0;
}
```
输出结果:
```
List 1: 1 3 5 7
List 2: 2 4 6 8
Merged List: 1 2 3 4 5 6 7 8
```