19:删除倒数第n个节点(remove nth node from end of list)

问题

Given a linked list, remove the n-th node from the end of list and return its head.
Example:
    Given linked list: 1->2->3->4->5, and n = 2.
    After removing the second node from the end, 
    the linked list becomes 1->2->3->5.
Note:
    Given n will always be valid.
Follow up:
    Could you do this in one pass?

代码

package com.itheima.test;

class Solution {

    public ListNode removeLastKthNode(ListNode head, int n) {
        ListNode start = new ListNode(0);
        ListNode slow = start, fast = start;
        slow.next = head;

        //Move fast in front so that the gap between slow and fast becomes n
        for(int i=0; i<=n; i++)   {   //注意此时fast指针移动了N+1次,移动到最后会到达null
            fast = fast.next;
        }
        //Move fast to the end, maintaining the gap
        while(fast != null) {       //如果删除每个链表的第一个节点,则不会进入此循环
            slow = slow.next;         //因为fast指针移动N+1次已经到了null
            fast = fast.next;
        }
        //Skip the desired node
        slow.next = slow.next.next;//这是指针的走向,不是赋值
        return start.next;

    }
}