思想:删除倒数第n个节点相当于删除正数第len-n+1个节点,要删去它,找其前驱
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null)return head;
int len = 0;
ListNode temp = head;
while(temp!=null){
len++;
temp = temp.next;
}
int k = len-n;//倒数第n个节点相当于正数第len-n+1个节点,要删去它,找其前驱
temp = head;
if(k==0){
return head.next;
}
while((--k)>0){
temp = temp.next;
}
temp.next = temp.next.next;
return head;
}
}