19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第 N 个结点

原题

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow = head;
        ListNode fast = head;
        //使得fast和slow之间相隔n-1个节点(fast比slow先走n步)
        for(int i=0;i<n;i++){
            fast=fast.next;
        }
        //说明删除的是头结点
        if(fast==null){
            return head.next;
        }
        //依次向后移动
        while(fast.next!=null){
            slow=slow.next;
            fast=fast.next;
        }
        //将slow指向下一个节点的后继结点(不能写slow.next=fast,举例[1,2])
        slow.next=slow.next.next;
        //返回结果
        return head;
    }
}
相关推荐
风落青芜1 天前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
风落青芜1 天前
C++入门:类和对象(三)
开发语言·数据结构·c++·算法
Pniubi1 天前
力扣25.K个一组反转链表
算法·leetcode·链表
杜 硕1 天前
从零开始的C++生活——第十五讲
开发语言·数据结构·c++·生活
小白的高手之路1 天前
【LeetCode 热题 100】560. 和为 K 的子数组|前缀和、哈希表(Python)
数据结构·笔记·python·算法·leetcode·力扣·散列表
蓝色汪洋1 天前
qsort使用指南
数据结构·算法
Code_Solitude1 天前
c语言:期末复习5(二维数组)
c语言·数据结构·算法
charliejohn1 天前
计算机考研 408 数据结构 散列表 平均查找长度 ASL
数据结构·散列表
charliejohn1 天前
计算机考研 408 数据结构 图的概念及例题
数据结构
Shaoshing1 天前
LeetCode100 32.最长有效括号
java·数据结构·leetcode