解题思路
整体思路是让前面的指针先移动n步,之后前后指针共同移动直到前面的指针到尾部为止。
首先设立预先指针 pre,预先指针是一个小技巧,在第2题中进行了讲解
设预先指针 pre 的下一个节点指向 head,设前指针为 first,后指针为 second,二者都等于 pre
first 先向前移动n步
-
之后 first 和 second 共同向前移动,此时二者的距离为 n,当 first 到尾部时,second 的位置恰好为倒数第 n 个节点的上一个结点。
立即学习“Java免费学习笔记(深入)”;
Java代码
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode first = pre;
ListNode second = pre;
while (n>0){
first= first.next;
n--;
}
while (first.next != null){
first=first.next;
second=second.next;
}
second.next = second.next.next;
return pre.next;
}
}











