通过两次扫描实现。ToDo:用一趟扫描实现
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { int length = 0; int pos; int count = 0; if(head == null){ return null; } ListNode curNode = head; //获取链表长度 while(curNode != null){ length++; curNode = curNode.next; } //正序位置,从0开始计数 pos = length - n; if(pos == 0){ return head.next; } curNode = head; while(true){ count++; if(count != pos){ curNode = curNode.next; }else{ curNode.next = curNode.next.next; break; } } return head; } }转载于:https://www.cnblogs.com/WillamZ/p/11478806.html