用c++写一个两个递增单链表合并成一个递增单链表
时间: 2024-03-24 22:27:26 浏览: 91
将两个有序链表合并一个链表
4星 · 用户满意度95%
#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 = l1;
tail = l1;
} else {
tail->next = l1;
tail = tail->next;
}
l1 = l1->next;
} else {
if (head == NULL) {
head = l2;
tail = l2;
} else {
tail->next = l2;
tail = tail->next;
}
l2 = l2->next;
}
}
if (l1 != NULL) {
tail->next = l1;
}
if (l2 != NULL) {
tail->next = l2;
}
return head;
}
int main() {
// 构造链表1
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;
// 构造链表2
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;
}
阅读全文