Leecode 0019. Remove Nth Node From End of List
19. Remove Nth Node From End of List
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Example 1:
1 | Input: head = [1,2,3,4,5], n = 2 |
Example 2:
1 | Input: head = [1], n = 1 |
Example 3:
1 | Input: head = [1,2], n = 1 |
题目大意
给定一个链表的头节点,要求删除链表的倒数第 N 个节点,并返回删除后的链表头节点。
解题思路
可以使用双指针法高效解决这个问题,只需一次遍历:
- 定义两个指针
fast
和slow
,初始都指向虚拟头节点 - 先让
fast
指针向前移动 N 步 - 然后让
fast
和slow
同时向前移动,直到fast
到达链表末尾 - 此时
slow
指针指向的就是要删除节点的前一个节点 - 通过调整指针删除目标节点
这种方法不需要先计算链表长度,时间效率更高。
1 | class Solution { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.