本题只要注意边界的条件就好了,防止空指针异常。
1.【1,2】删除倒数第2个节点的时候,fast会向后移动2步,因此会空指针异常,题目保证n是有效的,所以空指针异常的原因有且仅有是删除第一个节点导致的,所以,当fast为null时直接返回head.next即可。
for(int i=0;i<n;i++){
fast=fast.next;
if(fast==null) return head.next;//这里是如果要删除的是第一个节点 就会导致空指针异常
}
2.【1,2】,1这个案例中,cur指向1,fast指向2,而我们要删除的节点是cur的下一个节点,而不是fast;cur.next=cur.next.next;//这里的指向很重要 cur.next=fast;这是错误的 不要被案例迷惑了
贴一下正确的代码:
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode cur=head;
ListNode fast=head;
for(int i=0;i<n;i++){
fast=fast.next;
if(fast==null) return head.next;
}
while(fast.next!=null){
cur=cur.next;
fast=fast.next;
}
cur.next=cur.next.next;
return head;
}
}

京公网安备 11010502036488号