编程小白,写一个删除链表的倒数第n个节点的问题能通过,但是提交答案显示出错,求大神解答一下,谢谢
/**
};
/
class Solution {
public:
ListNode removeNthFromEnd(ListNode* head, int n){
int i;
ListNode *p1=head->next;
ListNode *p=head;;
while(p1 !=NULL && n>0){
p1=p1->next;
--n;
}
while(p1 !=NULL) {
p1=p1->next;
p=p->next;
};
p->next=p->next->next;
return head;
}
};
错误;Line 24: member access within null pointer of type 'struct ListNode'
你需要判断先走的指针是不是空指针
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = head;
ListNode* slow = head;
while(n>0) {
fast = fast -> next;
n--;
}
if(fast == NULL) {
if(head == NULL) {
return head;
} else {
return head -> next;
}
}
while(fast -> next) {
fast = fast -> next;
slow = slow -> next;
}
slow -> next = slow -> next -> next;
return head;
}
};
不知道你程序的24行是哪一行,但是根据提示,你可以排查下代码,你试图在访问一个NULL的指针。
没有考虑空指针吧,如果head==NULL,就会报错了