当前位置:网站首页>《剑指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; } } };
边栏推荐
- 【ManageEngine】什么是SIEM
- CAN总线的EMC设计方案
- lc marathon 7.26
- Code coverage statistical artifact -jacobo tool practice
- Internship: compilation of other configuration classes
- An example of building 3D effects on the web based on three.js
- Web page table table, realizing rapid filtering
- LeetCode 191. Number of 1 Bits(位1的个数) 位运算/easy
- Visual system design example (Halcon WinForm) -9. text display
- 反射
猜你喜欢
随机推荐
SkyWalking分布式系统应用程序性能监控工具-中
对话框管理器第三章:创建控件
Nefu117 number of prime numbers [prime number theorem]
反射
网络设备硬核技术内幕 路由器篇 10 CISCO ASR9900拆解 (三)
Web page table table, realizing rapid filtering
Principle of MOS tube to prevent reverse connection of power supply
多表查询_子查询概述和多表查询_子查询情况1&情况2&情况3
LeetCode 面试题 17.21. 直方图的水量 双指针,单调栈/hard
仅做两项修改,苹果就让StyleGANv2获得了3D生成能力
What is the execution method of the stand-alone parallel query of PostgreSQL?
网络设备硬核技术内幕 路由器篇 6 汤普金森漫游网络世界(中)
关于印发《深圳市工业和信息化局绿色制造试点示范管理暂行办法》的通知
LeetCode 190. 颠倒二进制位 位运算/easy
Disk troubleshooting of kubernetes node
CAN总线的EMC设计方案
周鸿祎:数字安全能力落后也会挨打
JUC(JMM、Volatile)
网络设备硬核技术内幕 路由器篇 18 DPDK及其前传(三)
ad7606与stm32连接电路介绍








