19. 删除链表的倒数第 N 个结点 + 链表 + 快慢指针

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

LeetCode_19

题目描述

代码实现

/**
 * 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 fast = head, slow = head, pre = null;
        for(int i=0; i<n; i++){
            if(fast != null)
                fast = fast.next;
            else return null;
        }
        while(fast != null){
            pre = slow;
            slow = slow.next;
            fast = fast.next;
        }
        if(pre == null){//需要删除的是头结点
            head = head.next;
        }else 
            pre.next = slow.next;//注意这里不是指向fast,因为fast此时一定为null
        return head;
    }
}
posted @ 2021-03-27 20:57  Garrett_Wale  阅读(49)  评论(0编辑  收藏  举报