题目是删除链表的倒数第N个节点

/**

  • Definition for singly-linked list.
  • public class ListNode {
  • int val;
  • ListNode next;
  • ListNode(int x) { val = x; }
  • } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head.next==null){ return null; } int count=0; ListNode first=head; while(head.next!=null){ count++; head=head.next; } if(count==n){ first=first.next; return first; } head=first; for(int i=1;i<count-n;i++){ head=head.next; } head.next=head.next.next; return first; } } 输入 [1,2,3,4,5] 2 正确输出 [1,2,3,5] 我的输出[1,2,4,5] 我不知道为啥错了

将for循环中的 i<count-n 改为 i<count-n+1,即for(int i=1;i<count-n+1;i++)试试,因为链表分配空间下标是从0开始的