[英]Why am I getting this error member access within null pointer of type 'ListNode'
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int count=0;
ListNode* temp2 = head;
ListNode* temp1 = head;
ListNode* temp = head;
while (temp != NULL)
{
++count;
temp = temp->next;
}
int i=1;
while(i!=(n-count) && temp1->next!=NULL && temp2->next!=NULL)
{
i++;
temp2=temp2->next;
temp1=temp1->next;
}
temp2=temp1->next; //move temp2 to next
temp2->val=temp1->val; //put val of temp2 to temp---so val erased
temp1->next=temp2->next; //adjust link
delete(temp2); //free
return head;
}
};
I got this error我收到这个错误
member access within null pointer of type 'struct ListNode'
null 类型“struct ListNode”指针中的成员访问
I did apply null checks, but I'm not able to detect the error.我确实应用了 null 检查,但我无法检测到错误。 It's about "Remove Nth Node From End of List".
这是关于“从列表末尾删除第 N 个节点”。
You need to rethink or clearly define what "nth" means.您需要重新思考或明确定义“第 n 个”的含义。
What about the corner cases?角落案例呢? Like -1 or 0 or count-1 or count or count+1.
比如 -1 或 0 或 count-1 或 count 或 count+1。
After that, please add some validation of the parameter "n".之后,请添加一些参数“n”的验证。
You have also one major problem in the code.您在代码中也有一个主要问题。 You mixed up
(count - n)
with 0(n - count)
你混淆了
(count - n)
和0(n - count)
A potential solution with assumptions on what nth means could be:假设 nth 意味着什么的潜在解决方案可能是:
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int count = 0;
ListNode* temp2 = head;
ListNode* temp1 = head;
ListNode* temp = head;
while (temp != nullptr)
{
++count;
temp = temp->next;
}
if ((count > 0) && (n>0) && ((count - n) > 0)) {
int i = 1;
while (i != (count - n) && temp1->next != nullptr && temp2->next != nullptr)
{
i++;
temp2 = temp2->next;
temp1 = temp1->next;
}
temp2 = temp1->next; //move temp2 to next
//temp2->val = temp1->val; //put val of temp2 to temp---so val erased
temp1->next = temp2->next; //adjust link
delete temp2; //free
return head;
}
}
};
int main() {
// Build linked list
ListNode *n5 = new ListNode(5);
ListNode* n4 = new ListNode(4, n5);
ListNode* n3 = new ListNode(3, n4);
ListNode* n2 = new ListNode(2, n3);
ListNode* n1 = new ListNode(1, n2);
ListNode* n0 = new ListNode(0, n1);
Solution solution;
solution.removeNthFromEnd(n0,6);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.