问题:给定一个链表,删除链表的倒数第 n 个节点并返回链表的头指针
思路:找到输出节点前一个节点,使用a.next=a.next.next覆盖掉需要删除的节点。
注意:要明确界限,因为是n+1,对n大于等于链表长度,需要进行边界判断。
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode a=head;
ListNode b=head;
int i=0;
while (b!=null){
if(i>=n+1){
a=a.next;
}
i++;
b=b.next;
}
if(i<n){
return null;
}else if (i==n){
return a.next;
}
a.next=a.next.next;
return head;
}