#21 合并两个有序链表(C)
(1)解题思路
step1
用 malloc 申请一个节点赋值给合并后的新链表 newList,将该节点作为 newList 的头结点。(应用头结点的目的是使得用“尾插法”合并链表时的操作保持一致)定义一个 rear 指针,指向 newList 的表尾。
step2
当 list1 和 list2 都不空时,依次比较 list1 和 list2 所指节点的值的大小,将值较小的节点用“尾插法”连接到 newList 的表尾。
step3
进行完 step2 后,list1 和 list2 必有一个为空,将不为空的那个链表直接连接到 newList 的表尾即可。
step4
返回时,返回 newList 的开始节点,不要将头结点返回。(newList 链表的数据是从开始节点存的,头节点里没有保存数据)
(2)代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <malloc.h>
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
//list1,list2不带头节点
struct ListNode* newList;
newList = (struct ListNode*)malloc(sizeof(struct ListNode)); //用newList指向合并后新的链表的头节点
newList -> next = NULL;
struct ListNode* rear = newList; //rear为指向新链表的表尾指针
//用“尾插法”建单链表的方法来实现list1和list2的合并
while(list1 != NULL && list2 != NULL){
if(list1 -> val <= list2 -> val){
rear -> next = list1;
list1 = list1 -> next;
rear = rear -> next;
}else{
rear -> next = list2;
list2 = list2 -> next;
rear = rear -> next;
}
}
//以下两条if语句必有一条会被执行
if(list1 != NULL){ //若list1还有未被并入的节点,则直接将其连接到新链表的表尾即可
rear -> next = list1;
}
if(list2 != NULL){ //若list2还有未被并入的节点,则直接将其连接到新链表的表尾即可
rear -> next = list2;
}
return newList -> next; //注意:返回的是合并后新链表的开始节点
}
分类:
LeetCode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构