当前位置:网站首页>【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
【勇敢饭饭,不怕刷题之链表】链表倒数节点问题
2022-08-10 10:41:00 【饭啊饭°】
前言
本系列主要整理面试中需要掌握的手撕代码题。本节介绍链表倒数节点问题。
一、BM8 链表中倒数最后k个结点
(1)定义快慢指针,首先让快指针走k个位置;
(2)然后让快慢指针同时移动,当快指针到末尾的时候,慢指针的位置就是倒数第k个。
function FindKthToTail( pHead , k ) {
// write code here
var fast = pHead;
var slow = pHead;
for(var i=0;i<k;i++){
if(fast==null){
return null
}
fast = fast.next;
}
while(fast){
fast = fast.next;
slow = slow.next;
}
return slow
}
二、BM9 删除链表的倒数第n个节点
(1)首先用上题的方法找到需要删除的节点,注意的就是定位到需要删除的前一个节点;
(2)判断要删除的是否是第一个节点,如果是,直接返回头节点的next;
(3)如果不是,则将该节点的next的next赋值给next。
function removeNthFromEnd( head , n ) {
// write code here
var slow = head;
var fast = head;
for(var i=0;i<n;i++){
if(fast == null){
return head
}
fast = fast.next
}
if(fast == null){
return head.next
}
while(fast.next!=null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next
return head
}
边栏推荐
- Will SQL and NoSQL eventually converge?
- JWT implements login authentication + Token automatic renewal scheme
- [Concept of Theory of Knowledge] "Progress in the Theory of Reason" University of Leuven 2022 latest 220-page doctoral dissertation
- 网络文化经营许可证
- 企业如何判断数据治理是否成功?
- [C language] Header file #include
, conio is Console Input/Output (console input and output) - Codeforces 814 C. An impassioned circulation of affection (dp)
- 文本选中圆角样式border-radius
- 谷歌数据中心发生“电力事故”造成 3 人受伤
- Dalian University of Technology & Pengcheng & UAE propose a mixed-scale triple network ZoomNet for camouflaged target detection, with SOTA performance!
猜你喜欢
Short video software development - how to break the platform homogenization
MongoDB数据库笔记
技能大赛训练题:组策略一
Research on motion capture system for indoor combined positioning technology
关于“码农”的一点自嘲解构
Text selection rounded style border-radius
第3章-线性方程组(3)
runtime-core.esm-bundler.js?d2dd:218 Uncaught TypeError: formRef.value?.validate is not a function
PPT | 「课件」企业中高层人员安全管理培训(118页)
ESP8266 教程1 — ESP8266硬件平台介绍
随机推荐
什么是抽象类
让软件飞——“X+”技术揭秘
POJ 1026 Cipher (置换群)
三相380V整流后的电压
数据库的约束
网络文化经营许可证
ECCV 2022 | 视频理解新框架X-CLIP:仅用微调的成本,达到预训练的全能
bus事件总线 使用
STM32 encapsulation ESP8266 a key configuration function: implementations of AP mode and the STA mode switch, server and the client to create
网络安全笔记5——数字签名
js对象转FormData对象(一般用于上传)
高阶组件使用
Situation丨The intrusion of hackers intensifies, and the shooting range sets up a "defense shield" for network security
C#List的使用以及Linq的使用
Flutter实战-请求封装(五)之Isolate线程改造
Load balancing principle analysis and source code interpretation
短视频软件开发——平台同质化如何破局
What is an abstract class
网络安全笔记6——数字证书与公钥基础设施
第3章-线性方程组(3)