当前位置:网站首页>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)
边栏推荐
猜你喜欢
随机推荐
腾讯超大 Apache Pulsar 集群的客户端性能调优实践
大佬们,这个测试demo只能获取到全量数据,不能获取增量,我的mysql 已经开启了row模式的bi
Ubuntu下使用sudo dpkg --configure -a后数据库出现问题
leetcode--541. 反转字符串II
sqllabs 1~6通关详解
Shell三剑客之sed命令详解
JS-BOM-名字转换器-输入名字位置颠倒
Brief description of the state of the thread
【愚公系列】华为云云数据库MySQL的体验流程|【华为云至简致远】
PAT甲级:1056 Mice and Rice
Streamsets Data Collector 3.12
我凭借这份pdf成功拿到了阿里,腾讯,京东等六家大厂offer
web-sql注入
兆骑科创创业赛事活动举办平台,投融资对接,线上直播路演
See how three years of CRUD programmers solve database deadlocks
一万块钱能做一手尿素期货吗?尿素期货怎么做才安全?
JS-BOM-Name Converter - Input Name Position Reversed
[内部资源] 想拿年薪30W的软件测试人员,这份资料必须领取
基于微信小程序的幼儿园招生报名系统开发笔记
WPF 常用布局方式









