当前位置:网站首页>【勇敢饭饭,不怕刷题之链表】有序链表的合并
【勇敢饭饭,不怕刷题之链表】有序链表的合并
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
}
边栏推荐
- Research on motion capture system for indoor combined positioning technology
- 14 high-frequency handwritten JS interview questions and answers to consolidate your JS foundation
- Mount [shell][mount -o loop]
- "Scalability" extensibility best practices: lessons from eBay
- OSSCore 开源解决方案介绍
- WebView2 通过 PuppeteerSharp 实现爬取 王者 壁纸 (案例版)
- [Azure Cloud] What is the difference between a service endpoint and a private link?point of view (1)
- Codeforces 814 C. An impassioned circulation of affection (dp)
- 首次入选OSDI顶会!腾讯提出超大规模推荐系统的模型低延时更新方案
- js猜拳小游戏源码
猜你喜欢

bus事件总线 使用

Redis6(一)——NoSQL数据库简介与Redis的安装

短视频软件开发——平台同质化如何破局

网络安全笔记6——数字证书与公钥基础设施

Memory problems difficult to locate, it is because you do not use ASAN

3 injured in 'electrical accident' at Google data center

Redis (three) - detailed configuration file, publish and subscribe, new data types

第5章相似矩阵及二次型(4)

MongoDB数据库笔记

"Time Series Database" uses cassandra to scan time series data
随机推荐
Will SQL and NoSQL eventually converge?
CodeChef STMRRG String Merging (dp)
1-IMU参数解析以及选择
关于“码农”的一点自嘲解构
这些年我开源的几个小项目
The impact of development mode on testing
Redis6(一)——NoSQL数据库简介与Redis的安装
C#List的使用以及Linq的使用
GPU accelerated Pinterest recommendation model, the number of parameters increased by 100 times, and the user activity increased by 16%
ESP8266 教程1 — ESP8266硬件平台介绍
三相380V整流后的电压
ISO9001在讲什么?过程方法和风险思维
14 high-frequency handwritten JS interview questions and answers to consolidate your JS foundation
Double.doubleToLongBits()方法使用
第3章-线性方程组(3)
HCIP ---- VLAN
2022.8.9-----leetcode.1413
AUTOCAD——减少样条曲线控制点数、CAD进阶练习(三)
「业务架构」介绍BPMN第二部分-泳道
Research on motion capture system for indoor combined positioning technology