当前位置:网站首页>《剑指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; } } };
边栏推荐
猜你喜欢

Why is there no unified quotation for third-party testing fees of software products?

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

工具 - markdown编辑器常用方法

关于 CMS 垃圾回收器,你真的懂了吗?

Design scheme of digital oscilloscope based on stm32

Getting started with DirectX

See "sense of security" in uncertainty Volvo asked in 2022

图解 SQL,这也太形象了吧

仅做两项修改,苹果就让StyleGANv2获得了3D生成能力

基于stm32的数字示波器设计方案
随机推荐
Kubernetes CNI 分类/运行机制
关于印发《深圳市工业和信息化局绿色制造试点示范管理暂行办法》的通知
STM32学习之CAN控制器简介
Unity最简洁的对象池实现
Stock trading 4
视觉系统设计实例(halcon-winform)-9.文字显示
Why is there no unified quotation for third-party testing fees of software products?
Notice on printing and distributing the Interim Measures for the administration of green manufacturing pilot demonstration of Shenzhen Bureau of industry and information technology
STM32F103C8T6在Arduino框架下驱动ssd1306 0.96“ IIC OLED显示
Graphical SQL is too vivid
Nefu119 combinatorial prime [basic theorem of arithmetic]
Introduction of the connecting circuit between ad7606 and stm32
[work] about technical architecture
南山区民政局关于开展2022年度南山区社会组织等级评估工作的通知
What is the execution method of the stand-alone parallel query of PostgreSQL?
网络设备硬核技术内幕 路由器篇 21 可重构的路由器
Passive income: return to the original and safe two ways to earn
周鸿祎:数字安全能力落后也会挨打
What is tor? What is the use of tor browser update?
Understand the evolution of redis architecture in one article