using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param n int整型 * @return ListNode类 */ public ListNode removeNthFromEnd (ListNode head, int n) { // write code here ListNode ahead=new ListNode(-1); ahead.next=head; ListNode a=ahead; ListNode b=ahead; while(n-->0) { a=a.next; //先走n步 } while(a.next!=null) { a=a.next; b=b.next; } b.next=b.next.next; return ahead.next; } } 考虑到可能删掉第一个,这里先借来一个链表,利用双指针,当前面的指针走到终点时,后面指针走到倒数第n个的前面,删除即可。