[https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-interview-150](19. 删除链表的倒数第 N 个结点)
mid(简单)
快慢指针
时间复杂度O(L) 空间复杂度O(1)
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// 创建一个哑节点,其next指向head,这样可以简化删除头节点的情况
ListNode dummy = new ListNode(0, head);
// first指针从head开始
ListNode first = head;
// second指针从dummy开始
ListNode second = dummy;
// 先将first指针向前移动n步
for (int i = 0; i < n; ++i) {
first = first.next;
}
// 然后first和second指针同时向前移动,直到first到达链表末尾
while (first != null) {
first = first.next;
second = second.next;
}
// 此时second指向要删除节点的前一个节点,删除节点
second.next = second.next.next;
// 返回新的头节点
ListNode ans = dummy.next;
return ans;
}
}
标签:head,ListNode,19,next,链表,second,节点,倒数第,first
From: https://www.cnblogs.com/qianingmeng/p/18294799