删除链路倒数第N个节点

采用快慢指针方法,先让两个指针都指向head节点,然后让fast先走N步,接着两个指针一起向前走。

如果fast已经到头了,那么slow的下一个就是要删除的节点。

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        ListNode slow = head;
        int i = 0;
        while (i < n) {
            fast = fast.next;
            i++;
        }
        // 删除头节点
        if (fast == null) {
            head  = head.next;
            return head;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}
原文地址:https://www.cnblogs.com/shuada/p/14205952.html