🟡 剑指 Offer II 021. 删除链表的倒数第 n 个结点
LeetCode 提示
题目难度 中等
原题链接 🔗 leetcode
#
题解1注意边界情况
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode pre = head; ListNode mock = new ListNode(); mock.next = head; for (int i=0; pre != null && i<n; i+=1) { pre = pre.next; } ListNode cur = mock; while (pre != null) { pre = pre.next; cur = cur.next; } ListNode ans = cur.next; cur.next = ans.next; ans.next = null; return mock.next; }}