19. 删除链表的倒数第 N 个结点
解题思路
链表,直接快慢指针,不是要删除第N个节点,我们就先定位到第N个节点,再删除就可以了。
但是本题要注意,我们是fast.next != null
就结束了,而不是fast != null
才结束,因为我们要到达的是第N个节点的前一个节点,这样才方便删除第N个节点,只要改一下前一个结点的指向就行了
代码
/**
* 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) {
if (head.next == null) return null;
ListNode slow = head;
ListNode fast = head;
while (n-- > 0) fast = fast.next;
if (fast == null) {
head = slow.next;
} else {
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
}
return head;
}
}