0
点赞
收藏
分享

微信扫一扫

代码随想录刷题--(链表篇)19. 删除链表的倒数第 N 个结点 ---快慢指针法

上古神龙 2022-05-05 阅读 55
javaleetcode

在这里插入图片描述
题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
代码随想录链接:https://programmercarl.com/0019.删除链表的倒数第N个节点.html#思路

/**
 * 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 dump = new ListNode(-1, head); 
        ListNode slow = dump; 
        
        //因为fast需要多走n+1步,才能使得slow正好为我们要去除的节点的前一位
        ListNode fast = dump.next; 
        while ((n--)>0 && fast != null) {
              fast = fast.next; 
        }
        while (fast != null) {
              fast = fast.next; 
              slow = slow.next; 
        }
        slow.next = slow.next.next; 
        return dump.next; 
    }
}

在这里插入图片描述

举报

相关推荐

0 条评论