https://leetcode.com/problems/remove-nth-node-from-end-of-list/
解题思路:
利用两个指针,slow 和 fast。首先让 fast 指针先走 n 步,这样的话 slow 和 fast 再一起走,直到 fast 等于 null 时 slow 所在的位置刚好的倒数第 n 个节点。
但是由于没有 prev 指针的存在,为了我们删除节点的方便,我们选择 slow 指针停在需要被删除节点的前一位(即:循环条件为 fast.next != null,而不是 fast != null),这样用 slow.next = slow.next.next 这句话就能很方便地删除节点。
还有一点要注意的是,不要忘记判断如果删除的节点是头节点,而这个链表只有一个节点的情况!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) return null;
ListNode slow = head, fast = head;
while (n != 0) {
fast = fast.next;
n--;
}
// if remove the first node
if (fast == null) return head.next;
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return head;
}
}