当前位置:网站首页>leetcode/delete the nth node from the bottom of the linked list
leetcode/delete the nth node from the bottom of the linked list
2022-08-08 15:14:00 【xcrj】
代码
package com.xcrj;
/** * 剑指 Offer II 021. 删除链表的倒数第 n 个结点 * 给定一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点. */
public class Solution21 {
/** * The two pointers move in the same direction,iPoints to the current node of the traversal,j指向从i倒数第n个结点,当i-j=n时,j移动,最终当i指向最后1个元素是,j指向倒数第n个元素 * Insert before the head node1个结点(伪头结点),It is not necessary to consider how to deal with the head node separately */
public ListNode removeNthFromEnd3(ListNode head, int n) {
// Construct a pseudo-header node,Inserted before the head of the linked list1个新的结点,The penultimate may not be processed separatelynA node is the head node
ListNode dummy = new ListNode(0, head);
ListNode pi = head;
ListNode pj = dummy;
// pi先走n步
for (int i = 0; i < n; ++i) {
pi = pi.next;
}
// pi和pj同时往后走,直到pireach the end point,此时pj就是倒数第n个结点
while (pi != null) {
pi = pi.next;
pj = pj.next;
}
pj.next = pj.next.next;
// The next node of the pseudo-head node is the head node
return dummy.next;
}
public static void main(String[] args) {
}
}
参考
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/SLwz0R/solution/shan-chu-lian-biao-de-dao-shu-di-n-ge-ji-ydte/
来源:力扣(LeetCode)
边栏推荐
猜你喜欢
随机推荐
761. 特殊的二进制序列 : 经典构造题
Synergistic authors open source throttling, 2022 trend of technology foresight (asynchronous programming/container technology)
PHP —— 用 ThinkPHP5.0 实现微信小程序登陆
如何成为团队核心?从写出不可维护的代码开始
全志V853芯片Tina下RTSP环境搭建方法
循环神经网络RNN入门介绍
Interview questions 17.05. Letters and numbers
bzoj3693 圆桌会议 hall定理+线段树
优雅地实时检测和更新 Web 应用
(1)通过FlinkSQL将数据写入mysql demo
光弘科技:公司在印度为小米、三星、OPPO、诺基亚提供智能手机等产品的制造服务
JS - BOM - - can be achieved through calculation or default values
IBM3650M4的ESXI主机报警“其他主机硬件对象的状态”
【控制】动力学建模举例 --> 牛顿-欧拉法
想要精准营销,从学习搭建一套对的标签体系开始丨 DTVision 分析洞察篇
leetcode/回文子字符串的个数
web自动化无头模式
分布式服务治理
JS-BOM-名字转换器-输入名字位置颠倒
Brief description of the state of the thread