先让一个指针走n-1步,然后俩个指针一起走就找到了要删除的节点。
import java.util.*;
public class Solution {
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode pre = head;
ListNode bac = head;
while((n-1)>0){
bac = bac.next;
n--;
}
ListNode prepre = null;
while(null != bac.next){
bac = bac.next;
prepre = pre;
pre = pre.next;
}
if(null == prepre){
return head.next;
}
prepre.next = prepre.next.next;
return head;
}
}