当前位置:网站首页>LeetCode 19. 删除链表的倒数第 N 个结点
LeetCode 19. 删除链表的倒数第 N 个结点
2022-06-26 04:56:00 【碳烤小肥羊。。。】
题目描述:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
思路解析:
指针的经典应用,如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了。
首先这里我推荐大家使用虚拟头结点,这样方便处理删除实际头结点的逻辑。
定义fast指针和slow指针,初始值为虚拟头结点,如图:
fast首先走n + 1步 ,为什么是n+1呢,因为只有这样同时移动的时候slow才能指向删除节点的上一个节点(方便做删除操作),如图:
fast和slow同时移动,直到fast指向末尾,如图:
删除slow指向的下一个节点,如图:
代码实现方式一:
public static ListNode removeNthFromEnd(ListNode head, int n) {
// 创建一个虚拟头结点
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
// 定义快慢指针
ListNode fast = dummyNode, slow = dummyNode;
// fast先走 n+1 步,这样slow就指向待删除结点的上一个结点
while (n >= 0){
fast = fast.next;
n--;
}
// fast,slow同时向后移送
while (fast != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummyNode.next;
}
代码实现方式二:
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
while (n > 0) {
fast = fast.next;
n--;
}
// 待删除节点slow 的上一节点
ListNode prev = null;
while (fast != null) {
prev = slow;
slow = slow.next;
fast = fast.next;
}
// 上一节点的next指针绕过 待删除节点slow 直接指向slow的下一节点
prev.next = slow.next;
return dummy.next;
}
边栏推荐
猜你喜欢
Créateur de génie: cavalier solitaire, magnat de la technologie et ai | dix ans d'apprentissage profond
5. < tag stack and general problems > supplement: lt.946 Verify the stack sequence (the same as the push in and pop-up sequence of offer 31. stack)
Dbeaver installation and configuration of offline driver
A new paradigm for large model application: unified feature representation optimization (UFO)
Database design (3): database maintenance and optimization
Differences between TCP and UDP
UWB超高精度定位系统架构图
Rsync common error messages (common errors on the window)
Stm8 MCU ADC sampling function is triggered by timer
超高精度定位系统中的UWB是什么
随机推荐
numpy 数据输入输出
numpy 通用函数
#微信小程序# 在小程序里面退出退出小程序(navigator以及API--wx.exitMiniProgram)
图解OneFlow的学习率调整策略
Why do many Shopify independent station sellers use chat robots? Read industry secrets in one minute!
Genius makers: lone Rangers, technology giants and AI | ten years of the rise of in-depth learning
Method of saving pictures in wechat applet
Multipass中文文档-远程使用Multipass
torchvision_ Transform (image enhancement)
5. < tag stack and general problems > supplement: lt.946 Verify the stack sequence (the same as the push in and pop-up sequence of offer 31. stack)
YOLOV5训练结果的解释
Differences between TCP and UDP
问题随记 —— pip 换源
Simple application of KMP
2022.2.16
Multipass Chinese document - use packer to package multipass image
Comment enregistrer une image dans une applet Wechat
Thymeleaf data echo, single selection backfill, drop-down backfill, time frame backfill
PSIM software learning ---08 call of C program block
Use fill and fill in Matplotlib_ Between fill the blank area between functions