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 if(head == null || head.next == null){ return null; } //第一步 计算链表的长度 int length = 0; ListNode ln = head; while(ln != null){ length ++; ln = ln.next; } //第二步 找到倒数第n个节点的前一个节点 int index = length - n; if(index == 0){ //头部删除 return head.next; } ListNode pre = head; for(int i =0;i<index-1;i++){ pre = pre.next; } //第三步 删除 拼接 pre.next = pre.next.next; return head; } }