题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/** * @author Lu.F * @version 1.0 * @date 2022/10/7 21:36 */ public class Solution { /** * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd(ListNode head, int n) { // write code here ListNode slow = head; ListNode fast = head; if (head == null) { return null; } // 快指针先走n步 for (int i = 0; i < n; i++) { fast = fast.next; } // 如果走出长度超出n,则删除的为头结点 if (fast == null){ return head.next; } // 当fast为null的时候走到末尾,同步向前 while (fast.next != null) { fast = fast.next; slow = slow.next; } // 删除第n个元素 slow.next = slow.next.next; return head; } }