合并两个有序链表用c语言编写完整代码
时间: 2023-11-30 20:03:09 浏览: 43
以下是合并两个有序链表的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;
}
}
ListNode* createList(int* nums, int size) {
ListNode* head = NULL;
ListNode** tail = &head;
for (int i = 0; i < size; i++) {
*tail = (ListNode*)malloc(sizeof(ListNode));
(*tail)->val = nums[i];
(*tail)->next = NULL;
tail = &((*tail)->next);
}
return head;
}
void printList(ListNode* head) {
while (head != NULL) {
printf("%d", head->val);
if (head->next != NULL) printf(" -> ");
head = head->next;
}
printf("\n");
}
int main() {
int nums1[] = {1, 3, 5, 7};
int nums2[] = {2, 4, 6, 8};
ListNode* l1 = createList(nums1, sizeof(nums1) / sizeof(int));
ListNode* l2 = createList(nums2, sizeof(nums2) / sizeof(int));
ListNode* merged = mergeTwoLists(l1, l2);
printList(merged);
return 0;
}
```
在主函数中,我们创建了两个有序链表l1和l2,然后调用mergeTwoLists函数将它们合并成一个有序链表merged,并调用printList函数打印输出结果。在createList函数中,我们使用双重指针tail来不断更新链表尾部,并返回链表头部。在mergeTwoLists函数中,我们使用递归方式将两个有序链表合并成一个有序链表。如果其中一个链表为空,我们直接返回另一个链表;否则,我们比较两个链表头部节点的值,将较小的节点作为合并后链表的头部,然后递归地将剩余的节点合并到该链表中。最后,我们返回合并后的链表头部。