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) { // write code here ListNode cur = head; int count = 0; while (cur != null) { count++; cur = cur.next; } if (n - count > 0) { return head; } int i = 0; ListNode preHead = new ListNode(-1); preHead.next = head; cur = preHead; while (i < count - n) { // 找到删除节点的前驱节点 i++; cur = cur.next; } cur.next = cur.next.next;// 删除 return preHead.next; } }