解题思路:用两个指针进行遍历,end指针与start指针之间相差n,当后面的指针为null时,删除此时end指针后面的节点即可,代码如下:
public static ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
ListNode start = head;
ListNode end = head;
if(head==null||head.next==null){
return null;
}
for(int i=0;i<n;i++) {
start = start.next;
}
if(start==null){
head = head.next;
return head;
}
start = start.next;
while(start!=null) {
start = start.next;
end = end.next;
}
end.next = end.next.next;
return head;
}