题目链接点击打开链接
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode head2=new ListNode(0);
head2.next=head;
ListNode forward=head;
for(int i=1;i<n;i++)
{
forward=forward.next;
}
ListNode tarPre=head2;
while(forward.next!=null)
{
forward=forward.next;
tarPre=tarPre.next;
}
ListNode result=tarPre.next;
if(result==head)
{
return result.next;
}
if(result.next==null)
{
tarPre.next=null;
}
else
{
tarPre.next=result.next;
}
return head;
}
}
本文详细介绍了如何通过迭代的方式,在不使用额外空间的情况下,找到并删除给定链表中倒数第N个节点的算法过程。通过引入虚拟头节点和双指针技巧,实现高效且简洁的链表操作。
293

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



