将两个递增的有序链表合并为一个递增的有序链表。要求结果链表仍用原来的存储空间,表中不允许有重复数据。C语言代码
时间: 2024-03-25 13:31:39 浏览: 66
两个有序链表的合并代码
5星 · 资源好评率100%
以下是合并两个递增有序链表的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
if (l1->val <= l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
int main() {
// 创建链表1: 1 -> 3 -> 5 -> 7
ListNode *l1 = (ListNode*)malloc(sizeof(ListNode));
l1->val = 1;
ListNode *node1 = (ListNode*)malloc(sizeof(ListNode));
node1->val = 3;
l1->next = node1;
ListNode *node2 = (ListNode*)malloc(sizeof(ListNode));
node2->val = 5;
node1->next = node2;
ListNode *node3 = (ListNode*)malloc(sizeof(ListNode));
node3->val = 7;
node2->next = node3;
node3->next = NULL;
// 创建链表2: 2 -> 4 -> 6 -> 8
ListNode *l2 = (ListNode*)malloc(sizeof(ListNode));
l2->val = 2;
ListNode *node4 = (ListNode*)malloc(sizeof(ListNode));
node4->val = 4;
l2->next = node4;
ListNode *node5 = (ListNode*)malloc(sizeof(ListNode));
node5->val = 6;
node4->next = node5;
ListNode *node6 = (ListNode*)malloc(sizeof(ListNode));
node6->val = 8;
node5->next = node6;
node6->next = NULL;
// 合并两个链表
ListNode *mergedList = mergeTwoLists(l1, l2);
// 输出合并后的链表
ListNode *p = mergedList;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
return 0;
}
```
输出结果为:1 2 3 4 5 6 7 8
阅读全文