题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
当链表长度小于n时,没有删除的数据,直接返回链表首位
当链表长度和N相同时,代表删除链表首位,更新首位为链表首位的next并返回
当链表长度大于N时,删除节点的上一节点连接到删除节点的下一节点
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) { ListNode p = head; ListNode pre = new ListNode(0); ListNode res = head; int length = 0; while (p != null) { length++; p = p.next; } p = head; int j = 0; if (n > length) return p; else if (n == length) { head = head.next; res = head; } else { for (int i = 1; i < length - n + 1; i++) { pre = head; head = head.next; } pre.next = head.next; } return res; } }