C语言实现两个非降序链表合并为新链表
C语言实现两个非降序链表的合并
问题描述
已知两个非降序链表序列 S1 和 S2,设计函数构造出 S1 和 S2 合并后的新的非降序链表 S3。
输入格式:
输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用 -1 表示序列的结尾(-1 不属于这个序列)。数字用空格间隔。
输出格式:
在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出 NULL。
输入样例:
1 3 5 -12 4 6 8 10 -1
输出样例:
1 2 3 4 5 6 8 10
C语言代码实现c#include <stdio.h>#include <stdlib.h>
// 定义链表节点结构体struct ListNode { int val; struct ListNode *next;};
// 合并两个非降序链表struct ListNode* mergeLists(struct ListNode* l1, struct ListNode* l2) { // 处理空链表情况 if (l1 == NULL) { return l2; } if (l2 == NULL) { return l1; }
// 创建虚拟头节点 struct ListNode dummy; struct ListNode* tail = &dummy;
// 循环比较两个链表节点的值 while (l1 && l2) { if (l1->val <= l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; }
// 连接剩余的节点 tail->next = l1 ? l1 : l2;
// 返回虚拟头节点的下一个节点,即合并后的链表头节点 return dummy.next;}
// 打印链表void printList(struct ListNode* list) { struct ListNode* curr = list; while (curr) { printf('%d ', curr->val); curr = curr->next; } printf(' ');}
// 主函数int main() { struct ListNode* l1 = NULL; struct ListNode* l2 = NULL; struct ListNode* l3 = NULL;
int num; // 读取第一个链表 scanf('%d', &num); while (num != -1) { struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val = num; newNode->next = NULL;
if (l1 == NULL) { l1 = newNode; } else { struct ListNode* curr = l1; while (curr->next) { curr = curr->next; } curr->next = newNode; }
scanf('%d', &num); } // 读取第二个链表 scanf('%d', &num); while (num != -1) { struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val = num; newNode->next = NULL;
if (l2 == NULL) { l2 = newNode; } else { struct ListNode* curr = l2; while (curr->next) { curr = curr->next; } curr->next = newNode; }
scanf('%d', &num); }
// 合并两个链表 l3 = mergeLists(l1, l2); // 打印合并后的链表 printList(l3);
return 0;}
代码解析
- 定义链表节点结构体: 使用
struct ListNode定义链表节点,包含数据域val和指针域next。2. mergeLists 函数: - 首先处理输入链表为空的情况。 - 创建虚拟头节点dummy,方便操作。 - 使用tail指针遍历新链表,将较小的节点连接到tail后面。 - 最后将剩余节点连接到tail后面。 - 返回dummy.next,即合并后的链表头节点。3. printList 函数: 遍历链表并打印每个节点的值。4. main 函数: - 读取两个链表的数据。 - 调用mergeLists函数合并链表。 - 调用printList函数打印合并后的链表。
时间复杂度
该算法的时间复杂度为 O(n+m),其中 n 和 m 分别是两个链表的长度。
总结
本文使用 C 语言实现了两个非降序链表的合并,并提供了详细的代码解析和时间复杂度分析。该算法思路清晰,代码简洁易懂,适合学习和参考。
原文地址: https://www.cveoy.top/t/topic/bF82 著作权归作者所有。请勿转载和采集!