题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd (ListNode head, int n) { if (head == null) return null; ListNode res = head; ArrayList<ListNode> list = new ArrayList<>(); ListNode temp = head; ListNode q = null; while (temp != null) { ListNode node = new ListNode(temp.val); list.add(node); temp = temp.next; } int size = list.size(); if (size < n) return null; for (int i = 0 ; i < size - n; i++) { q = head; head = head.next; } if (q == null) { q = head; head = head.next; q.next = null; return head; } ListNode next = head.next; head.next = null; q.next = next; return res; } }