package 链表;
/**
* https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
* 19. 删除链表的倒数第N个节点
* 思路:采用快慢指针,让快指针先走n步,慢指针从头开始,如果快指针的下一个节点为null,
* 说明此时慢指针当前的节点就是要删除的节点,需要将慢指针指向下下个节点(跳过下一个节点)
*/
public class _19_Remove_Nth_Node_From_End_of_List {
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head;
while (n-- > 0) {
fast = fast.next;
}
if (fast == null) {
return head.next;
}
ListNode slow = head;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}
}
原文:https://www.cnblogs.com/jianzha/p/12838029.html