/** * 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 t1=head; ListNode t2=head; ListNode last=null; for(int i=0;i<n;i++) { t1=t1.next; } while(t1!=null) { t1=t1.next; last=t2; t2=t2.next; } if(last==null) { //去头 return head.next; } else { last.next=last.next.next; } return head; } }
本文介绍了一种高效的方法来删除单链表中倒数第N个节点。通过使用双指针技巧,避免了二次遍历链表的需求。文章提供了完整的Java实现代码,并解释了其工作原理。
518

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



