用C语言将两个递增的有序链表合并为一个递增的有序链表
时间: 2023-10-18 20:19:18 浏览: 60
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
if (head == NULL) {
head = tail = l1;
}
else {
tail->next = l1;
tail = l1;
}
l1 = l1->next;
}
else {
if (head == NULL) {
head = tail = l2;
}
else {
tail->next = l2;
tail = l2;
}
l2 = l2->next;
}
}
if (l1 != NULL) {
tail->next = l1;
}
if (l2 != NULL) {
tail->next = l2;
}
return head;
}
int main() {
struct ListNode* l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = 1;
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 3;
l1->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->next->val = 5;
l1->next->next->next = NULL;
struct ListNode* l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->val = 2;
l2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->val = 4;
l2->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->next->val = 6;
l2->next->next->next = NULL;
struct ListNode* merged = mergeTwoLists(l1, l2);
while (merged != NULL) {
printf("%d ", merged->val);
merged = merged->next;
}
printf("\n");
return 0;
}
```
阅读全文