📅  最后修改于: 2023-12-03 14:59:39.451000             🧑  作者: Mango
有两个链表L1和L2,现在需要将L2合并到L1的交替位置上,即L2的第一个节点插入到L1的第一个节点后面,L2的第二个节点插入到L1的第二个节点后面,以此类推。
思路:先将L2完全合并到L1的尾部,然后再将L1和L2交替连接起来。
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int value;
struct ListNode *next;
} ListNode;
ListNode *mergeAlternate(ListNode *L1, ListNode *L2) {
if (!L1 && !L2) // 如果两个链表都为空,则返回NULL
return NULL;
if (!L1) // 如果L1为空,则返回L2合并后的链表
return L2;
if (!L2) // 如果L2为空,则返回L1合并后的链表
return L1;
ListNode *curr1 = L1;
ListNode *curr2 = L2;
ListNode *tail = NULL; // 用于记录L1的尾节点
while (curr1->next) { // 找到L1的尾节点
curr1 = curr1->next;
}
tail = curr1;
tail->next = curr2; // 将L2完全合并到L1的尾部
curr1 = L1;
curr2 = L2;
while (curr2) { // 将L2的节点依次插入到L1的交替位置上
ListNode *temp1 = curr1->next;
ListNode *temp2 = curr2->next;
curr1->next = curr2;
curr2->next = temp1;
curr1 = temp1;
curr2 = temp2;
}
return L1;
}
int main() {
/* 构造链表L1: 1->3->5->7 */
ListNode *n1 = (ListNode*)malloc(sizeof(ListNode));
n1->value = 1;
ListNode *n3 = (ListNode*)malloc(sizeof(ListNode));
n3->value = 3;
ListNode *n5 = (ListNode*)malloc(sizeof(ListNode));
n5->value = 5;
ListNode *n7 = (ListNode*)malloc(sizeof(ListNode));
n7->value = 7;
n1->next = n3;
n3->next = n5;
n5->next = n7;
n7->next = NULL;
/* 构造链表L2: 2->4->6 */
ListNode *n2 = (ListNode*)malloc(sizeof(ListNode));
n2->value = 2;
ListNode *n4 = (ListNode*)malloc(sizeof(ListNode));
n4->value = 4;
ListNode *n6 = (ListNode*)malloc(sizeof(ListNode));
n6->value = 6;
n2->next = n4;
n4->next = n6;
n6->next = NULL;
ListNode *merged = mergeAlternate(n1, n2);
/* 打印合并后的链表 */
ListNode *curr = merged;
while (curr) {
printf("%d ", curr->value);
curr = curr->next;
}
printf("\n");
return 0;
}
输入:
链表L1: 1->3->5->7
链表L2: 2->4->6
输出:
1 2 3 4 5 6 7