当前位置:网站首页>【勇敢饭饭,不怕刷题之链表】有序链表的合并
【勇敢饭饭,不怕刷题之链表】有序链表的合并
2022-08-10 10:41:00 【饭啊饭°】
前言
本系列主要整理面试中需要掌握的手撕代码题。本节介绍有序链表的合并。
一、BM4 合并两个排序的链表

(1)首先新建一个空链表,并定义一个新指针指向空链表;
(2)如果两个链表都不为空,则比较当前两个链表的值,选择小的加入空链表,并移动指针;
(3)当出现空链表后,就把非空链表都接在新链表后面,最后返回头部指针。
代码如下:
function Merge(pHead1, pHead2)
{
// write code here
var newHead = new ListNode();
var p = newHead;
while(pHead1 && pHead2){
if(pHead1.val > pHead2.val){
p.next = pHead2;
pHead2 = pHead2.next;
}else{
p.next = pHead1;
pHead1 = pHead1.next;
}
p = p.next;
}
p.next = (!pHead1) ? pHead2 : pHead1
return newHead.next
}
二、BM5 合并k个已排序的链表

(1) 依次遍历链表中的val,都存放在一个新列表中;
(2)对新列表进行排序;
(3)遍历新列表,不断创建新节点,将新列表变为新链表,并返回。
function mergeKLists( lists ) {
// write code here
var newlist = [];
lists.forEach(item=>{
while(item){
newlist.push(item.val)
item = item.next
}
})
newlist.sort((a,b)=> {
return a-b})
var newNode = new ListNode();
var p = newNode;
newlist.forEach(item=>{
var q = new ListNode(item);
p.next = q;
p = p.next
})
return newNode.next
}
边栏推荐
- WebView2 通过 PuppeteerSharp 实现爬取 王者 壁纸 (案例版)
- 网络安全笔记5——数字签名
- 动作捕捉系统用于室内组合定位技术研究
- [Concept of Theory of Knowledge] "Progress in the Theory of Reason" University of Leuven 2022 latest 220-page doctoral dissertation
- 突破次元壁垒,让身边的玩偶手办在屏幕上动起来!
- ZZULIOJ 1116 Delete elements [delete]
- 「业务架构」介绍BPMN第二部分-泳道
- bus事件总线 使用
- Mount [shell][mount -o loop]
- Interviewer: Dao, in Service, the Controller, Util, divided into the Model?
猜你喜欢

兼容移动和PC的loading加载和toast消息插件

1-IMU参数解析以及选择
![[C language] Floating point number rounding](/img/ff/3f256deaa5ec82d692828c67cfb0fa.png)
[C language] Floating point number rounding

关于“码农”的一点自嘲解构

首次入选OSDI顶会!腾讯提出超大规模推荐系统的模型低延时更新方案

Situation丨The intrusion of hackers intensifies, and the shooting range sets up a "defense shield" for network security

mysql5.7安装部署-yum安装

Mobile and PC compatible loading and toast message plugins

网络安全笔记5——数字签名

ECCV 2022 | 视频理解新框架X-CLIP:仅用微调的成本,达到预训练的全能
随机推荐
2023版揽胜运动曝光,安全、舒适一个不落
What is an abstract class
owl.carousel poster card Slider carousel switch
兼容移动和PC的loading加载和toast消息插件
ZZULIOJ 1116 删除元素【删】
PTA 7-2 Summation and Counting of Diagonal Elements of Square Matrices Solution
ZZULIOJ 1116 Delete elements [delete]
2022.8.8-----leetcode.761
ESP8266 教程1 — ESP8266硬件平台介绍
Text selection rounded style border-radius
C#实战:基于ItextSharp技术标签生成小工具
从产品维度来看 我们为什么不能完全信任Layer2?
Redis (three) - detailed configuration file, publish and subscribe, new data types
【Azure云】服务端点和私有链接有什么区别?观点(1)
leetcode:334. 递增的三元子序列
Flutter实战-请求封装(五)之Isolate线程改造
自动化测试及Selenium
让软件飞——“X+”技术揭秘
js猜拳小游戏源码
交换 生成树 知识总结