当前位置:网站首页>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)
边栏推荐
猜你喜欢
随机推荐
Superset 1.2.0 安装
bandanas Kerchief头巾是何含义?
什么是低代码开发?大家都真的看好低代码开发吗?
JDBC工具类的封装及使用
你真的会软件测试bug分析定位嘛
投资一个约20台桩的充电站需要多少钱?多久可以实现盈利?
Zhaoqi Technology Innovation and Entrepreneurship Event Event Platform, Investment and Financing Matchmaking, Online Live Roadshow
【Unity入门计划】用双血条方法控制伤害区域减血速度
深度学习-神经网络原理1
Chat with wine and chat, build an asynchronous non-blocking (aioredis) real-time (websocket) communication chat system based on Vue3.0+Tornado6.1+Redis publish-subscribe (pubsub) mode
vijos1212 Way Selection
分布式服务治理
JS-Bom-while(计算闰年)
基于微信小程序的幼儿园招生报名系统开发笔记
RecyclerView 实现拖拽、滑动删除
瑞吉外卖学习笔记2
“科林明伦杯”哈尔滨理工大学暑假训练赛 B吃雪糕 (异或思维题)(补题)
【Kaggle】Save My Paper 基于自编码器的文本图像去噪
JS Adder (DOM)
JS-BOM-Name Converter - Input Name Position Reversed