力扣题目链接:删除链表的倒数第 n 个结点
一次遍历完成:如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了。
/**
* 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 slow = head;
// 移动快指针
ListNode quick = head;
while (quick.next != null) {
// 移动快指针
if (n>0) {
quick = quick.next;
n--;
}
// 同时移动快慢指针
else {
quick = quick.next;
slow = slow.next;
}
}
if (slow.next == null || slow == null) {
return null;
}
// n!=0
if (n==1) {
head = head.next;
}
// n=0
else {
slow.next = slow.next.next;
}
return head;
}
}