当前位置:网站首页>链表(五)——删除链表的倒数第N个节点
链表(五)——删除链表的倒数第N个节点
2022-07-20 15:48:00 【木棣%】
删除链表的倒数第N个节点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点
示例 :
输入: head = [1,2,3,4,5], n = 2
提示:
- 链表中结点的数目为 sz
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
双指针
要删除倒数第n
个节点,让p
移动n
步,然后让p
和q
同时移动,直到p
指向链表末尾
删掉q
所指向的节点
- 设置虚拟节点
dummyHead
指向head
- 设定双指针
p
和q
,初始都指向虚拟节点dummyHead
- 移动
q
,直到p
与q
之间相隔的元素个数为n
- 同时移动
p
与q
,直到q
指向的为NULL
- 将
p
的下一个节点指向下下个节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode p = dummyHead;
ListNode q = dummyHead;
while (n-- > 0) {
p = p.next;
}
// 待删除节点q的上一节点
ListNode prev = null;
while (p != null) {
prev = q;
q = q.next;
p = p.next;
}
// 上一节点的next指针绕过 待删除节点q 直接指向q的下一节点
prev.next = q.next;
// 释放 待删除节点q 的next指针
q.next = null;
return dummyHead.next;
}
}
边栏推荐
- Xperia XZ (F8332) 刷机和ROOT过程中遇到的一些问题的解答
- 在VB6 处理pdf 和jpg文件
- dpkg : Breaks: libapt-pkg5.0 (< 1.7~b) but 1.6.15 is to be installedE: Broken packages
- C语言程序环境和预处理
- At the same time, RF interference signal inspection and mitigation are realized
- MFC关闭预编译头文件后错误解决
- codeforces educational round 131 ABCDEF
- 2.负载测试
- SQLite 数据库操作
- MySQL ON DELETE CASCADE(级联删除)[猿教程]
猜你喜欢
Hide & seek introduction -- end-to-end simulation and processing of radio observation data (I)
Machine learning - detailed derivation of support vector machine theory (including explanation of examples) (II)
[vs2019] create C project
在 Excel 内使用 ODBC 消费 SAP ABAP CDS view
redis 内存分析工具 RMA 使用
50个名额限量开放|带着OceanBase年度发布会的消息走来了!
4 个简单操作,实现 CPU 轻量级网络 ---- PP-LCNet: A Lightweight CPU Convolutional Neural Network
91.(leaflet篇)leaflet态势标绘-进攻方向绘制
[论文速度] 同时解决成像时,曝光不足和曝光过度问题:Deep Reciprocating HDR Transformation
重磅预告!易观分析联合微软、中央财经大学,共话数字经济
随机推荐
RS笔记:工业界推荐系统YouTubeDNN模型(召回层+排序层)[2016 YouTube]
Example of unity custom attribute
学会这些Jmeter插件,才能设计出复杂性能测试场景
User experience | deeply cultivate user experience and build a moat for bank competition
一篇文章快速复习flex属性与用法
Macro create inline function read / write CPU reg
Relation et différence entre la cartographie des fichiers (mmap) et sendfile et zéro copie
Semantic segmentation-rethinking bisenet for real time semantic segmentation-2-miou calculation
1.smoke测试
At the same time, RF interference signal inspection and mitigation are realized
Hide & seek introduction -- end-to-end simulation and processing of radio observation data (I)
机器学习—支持向量机理论详细推导(含例题讲解)(一)
简单运行k6
[neurips 2021] tokenlearner: number and location of adaptive learning tokens - what can 8 learned tokens do for images and videos?
Kalman filter meets deep learning: papers related to Kalman filter and deep learning
Semantic segmentation -rethinking bisenet for real time semantic segmentation-1-cityscapes dataset
openGauss内核分析:查询重写
关于字符串的分割问题
Pandoc installation, use and quick start
重磅预告!易观分析联合微软、中央财经大学,共话数字经济