#include <stdio.h>
#include <stdlib.h>
/* 定义链表节点结构体 */
struct ListNode {
int val;
struct ListNode* next;
};
/* 合并两个递增有序链表 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
/* 如果其中一个链表为空,则直接返回另一个链表 */
if (!l1) {
return l2;
}
if (!l2) {
return l1;
}
/* 定义指针 p 和 q 分别指向两个链表的头结点 */
struct ListNode* p = l1, * q = l2;
/* 定义结果链表的头结点和尾结点 */
struct ListNode* head = NULL, * tail = NULL;
/* 比较两个链表中节点的大小,并将较小的节点加入结果链表中 */
while (p && q) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
if (p->val < q->val) {
node->val = p->val;
p = p->next;
}
else {
node->val = q->val;
q = q->next;
}
if (!head) {
head = tail = node;
}
else {
tail->next = node;
tail = tail->next;
}
}
/* 将剩余的节点加入结果链表中 */
if (p) {
tail->next = p;
}
if (q) {
tail->next = q;
}
return head;
}
/* 从键盘输入链表 */
struct ListNode* inputList() {
int n;
scanf_s("%d", &n);
if (n == 0) {
return NULL;
}
struct ListNode* head = NULL, * tail = NULL;
for (int i = 0; i < n; i++) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
scanf_s("%d", &node->val);
node->next = NULL;
if (!head) {
head = tail = node;
}
else {
tail->next = node;
tail = tail->next;
}
}
return head;
}
/* 输出链表 */
void printList(struct ListNode* head) {
while (head) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
/* 从键盘输入两个链表 */
printf("请输入第一个链表的节点数:");
struct ListNode* l1 = inputList();
printf("请输入第二个链表的节点数:");
struct ListNode* l2 = inputList();
/* 合并两个链表 */
struct ListNode* result = mergeTwoLists(l1, l2);
/* 输出结果链表 */
printf("合并后的链表为:");
printList(result);
return 0;
}