Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
Example 1
1 | Given linked list: 1->2->3->4->5, and n = 2. |
解题思路
双指针 p
和 q
。两指针相距 n
,移动两个指针直至 q
到达末尾。此时 p
指向待删除节点的前面。当删除第一个节点时,需要增加哑节点。
复杂度分析
- 时间复杂度:$O(n)$
- 空间复杂度:$O(1)$
代码
1 | /** |