两个有序链表的合并c
时间: 2024-06-12 13:08:26 浏览: 20
两个有序链表的合并可以通过遍历两个链表,比较节点的值,将较小的值插入到一个新的链表中。具体的实现可以参考下面的示例代码:
```c
#include<stdio.h>
#include<stdlib.h>
// 定义链表节点的结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建一个新的节点
struct ListNode* createNode(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) {
// 创建一个新的链表头节点
struct ListNode* dummyNode = createNode(0);
struct ListNode* current = dummyNode;
// 遍历两个链表
while (l1 != NULL && l2 != NULL) {
// 比较节点的值,将较小的节点插入到新链表中
if (l1->val <= l2->val) {
current->next = l1;
l1 = l1->next;
} else {
current->next = l2;
l2 = l2->next;
}
current = current->next;
}
// 将剩余的节点插入到新链表中
if (l1 != NULL) {
current->next = l1;
}
if (l2 != NULL) {
current->next = l2;
}
return dummyNode->next;
}
// 打印链表
void printList(struct ListNode* head) {
struct ListNode* current = head;
while (current != NULL) {
printf("%d ", current->val);
current = current->next;
}
printf("\n");
}
int main() {
// 创建两个有序链表
struct ListNode* l1 = createNode(1);
l1->next = createNode(2);
l1->next->next = createNode(4);
struct ListNode* l2 = createNode(1);
l2->next = createNode(3);
l2->next->next = createNode(4);
// 合并两个链表
struct ListNode* mergedList = mergeTwoLists(l1, l2);
// 打印合并后的链表
printList(mergedList);
// 释放链表的内存
struct ListNode* current = mergedList;
while (current != NULL) {
struct ListNode* temp = current;
current = current->next;
free(temp);
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)