当前位置:网站首页>《剑指Offer》 合并两个排序的链表
《剑指Offer》 合并两个排序的链表
2022-07-27 14:15:00 【傻子是小傲娇】
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
Solution1:
如果一个为空,则返回另一个。当两个都不为空时,比较大小选择小的那个加入新建的链表中,直到一方为空。
最后将不为空的链表加到新建链表的尾部。
Solution2:
递归解法
Solution1:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2){ if (!pHead1)return pHead2; if (!pHead2)return pHead1; ListNode *p, *q, *head = nullptr; while (pHead1&&pHead2){ if (pHead1->val < pHead2->val){ p = pHead1; pHead1 = pHead1->next; } else{ p = pHead2; pHead2 = pHead2->next; } if (head == nullptr){ head = q = p; } else{ q->next = p; q = p; } } if (pHead1)p->next = pHead1; if (pHead2)p->next = pHead2; return head; } };Solution2:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1==null)return pHead2; if(pHead2==null)return pHead1; if(pHead1->val<pHead2->val){ pHead1->next=Merge(pHead1->next,pHead2); return pHead1; }else{ pHead2->next=Merge(pHead1,pHead2->next); return pHead2; } } };
边栏推荐
- Web page table table, realizing rapid filtering
- Dynamic programming - stock trading 5
- 网络设备硬核技术内幕 路由器篇 20 DPDK (五)
- Design scheme of digital oscilloscope based on stm32
- 图解 SQL,这也太形象了吧
- 事务_基本演示和事务_默认自动提交&手动提交
- 《剑指Offer》剪绳子
- Nokia's patent business was hit for the first time, and Chinese enterprises are not so easy to knead
- 网络设备硬核技术内幕 路由器篇 17 DPDK及其前传(二)
- STM32 can -- can ID filter analysis
猜你喜欢

修改frameworks资源文件如何单编

LeetCode 74. 搜索二维矩阵 二分/medium

基于FIFO IDT7202-12的数字存储示波器

RS485接口的EMC设计方案

4种单片机驱动继电器方案

Zhou Hongyi: if the digital security ability is backward, it will also be beaten

腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?

视觉系统设计实例(halcon-winform)-9.文字显示
Principle of MOS tube to prevent reverse connection of power supply

视觉系统设计实例(halcon-winform)-10.PLC通讯
随机推荐
Hdu3117 Fibonacci numbers [mathematics]
Stm32f103c8t6 drives ssd1306 0.96 "IIC OLED display under Arduino frame
STM32之CAN ---CAN ID过滤器分析
[ManageEngine] what is Siem
LeetCode 81. 搜索旋转排序数组 II 二分/medium
NEFU118 n!后面有多少个0【算术基本定理】
Nokia's patent business was hit for the first time, and Chinese enterprises are not so easy to knead
如何帮助企业优化Office管理
lc marathon 7.26
USB接口电磁兼容(EMC)解决方案
网络设备硬核技术内幕 路由器篇 14 从鹿由器到路由器 (中)
仪表放大器和运算放大器优缺点对比
Principle of MOS tube to prevent reverse connection of power supply
JUC(JMM、Volatile)
[Yunxiang book club issue 13] packaging format of video files
Unity最简洁的对象池实现
SkyWalking分布式系统应用程序性能监控工具-中
Confirm the time accuracy of the power supply setting voltage through the i/o function of vn1630/vn7640
OBS advanced DXGI acquisition screen process, and how to modify it to its own cursor
2022-07-27日报:IJCAI 2022杰出论文公布,大陆作者中稿298篇拿下两项第一