qq_39064700 2018-10-10 13:00 采纳率: 0%
浏览 763

题目是删除链表的倒数第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] 我不知道为啥错了
  • 写回答

1条回答 默认 最新

  • JIALIH_H 2018-10-10 14:32
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器