当前位置: 代码迷 >> 综合 >> [leetcode] 19. Remove Nth Node From End of List (Medium)
  详细解决方案

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

热度:61   发布时间:2024-01-05 01:05:01.0

原题链接

删除单向链表的倒数第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;}
}
  相关解决方案