/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null)
return null;
int i = 0;
ListNode tail = head;
ListNode node = head;
while(i++ < n){
tail = tail.next;
}
if(tail == null)
return head.next;
while(tail.next != null){
tail = tail.next;
node = node.next;
}
node.next = node.next.next;
return head;
}
}Remove Nth Node from End of List
最新推荐文章于 2024-06-20 12:29:29 发布
本文介绍了一种高效的方法来删除给定链表中的倒数第N个节点。通过使用双指针技巧,文章详细解释了如何在一次遍历中找到目标节点并将其移除。此外还提供了完整的Java代码实现。
623

被折叠的 条评论
为什么被折叠?



