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;
    }
}
相关推荐
Yeats_Liao16 小时前
MindSpore开发之路(八):数据处理之Dataset(上)——构建高效的数据流水线
数据结构·人工智能·python·机器学习·华为
客梦17 小时前
数据结构-线性表
数据结构·笔记
鹿角片ljp17 小时前
力扣226.翻转二叉树-递归
数据结构·算法·leetcode
WBluuue17 小时前
数据结构和算法:Morris遍历
数据结构·c++·算法
客梦17 小时前
数据结构-红黑树
数据结构·笔记
Sheep Shaun18 小时前
STL:string和vector
开发语言·数据结构·c++·算法·leetcode
winfield82118 小时前
滑动时间窗口,找一段区间中的最大值
数据结构·算法
k***921619 小时前
list 迭代器:C++ 容器封装的 “行为统一” 艺术
java·开发语言·数据结构·c++·算法·list
x70x8020 小时前
C++中auto的使用
开发语言·数据结构·c++·算法·深度优先
sin_hielo20 小时前
leetcode 2054(排序 + 单调栈,通用做法是 DP)
数据结构·算法·leetcode