[leetcode] 19. Remove Nth Node From End of List (Medium)

it2025-11-11  8

原题链接

删除单向链表的倒数第n个结点。

思路: 用两个索引一前一后,同时遍历,当后一个索引值为null时,此时前一个索引表示的节点即为要删除的节点。 Runtime: 13 ms, faster than 24.49% of Java

class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode slow=head; ListNode fast=head; for(int i=0;i<n;i++) fast=fast.next; if (fast==null){ return head.next; } while(fast.next!=null) { slow=slow.next; fast=fast.next; } slow.next=slow.next.next; return head; } }

转载于:https://www.cnblogs.com/ruoh3kou/p/9952478.html

相关资源:数据结构—成绩单生成器
最新回复(0)