解法:快慢指针
快指针先走n步,然后再和慢指针一起走,此时当快指针走完的时候,慢指针则刚好走到倒数的第n+1个结点,跳过倒数的第n个结点
public class Solution { /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd (ListNode head, int n) { // write code here if(head==null || n<1){ return null; } ListNode fast=head; ListNode slow=head; for(int i=0;i<n;i++){ fast=fast.next; } //如果n的值等于链表的长度,直接返回去掉头结点的链表 if(fast==null){ return head.next; } //走到倒数的第n+1个结点 while(fast.next!=null){ fast=fast.next; slow=slow.next; } //跳过倒数的第n个结点 slow.next=slow.next.next; return head; } }