整体思路是让前面的指针先移动n步,之后前后指针共同移动直到前面的指针到尾部为止。
首先设立预先指针 pre,预先指针是一个小技巧,在第2题中进行了讲解
设预先指针 pre 的下一个节点指向 head,设前指针为 first,后指针为 second,二者都等于 pre
first 先向前移动n步
之后 first 和 second 共同向前移动,此时二者的距离为 n,当 first 到尾部时,second 的位置恰好为倒数第 n 个节点的上一个结点。
立即学习“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;
}
}以上就是Java怎么删除链表的倒数第N个节点的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号