[英]runtime error: member access within null pointer of type 'ListNode' - Clone a linked list
I am trying to clone a linked list in reverse order.我正在尝试以相反的顺序克隆链表。
ListNode* cloneList(ListNode* head) {
ListNode *prev = new ListNode(head->val);
head = head->next;
while (head != NULL)
{
ListNode *p = new ListNode(head->val, prev);
head = head->next;
prev = p;
}
return prev;
}
The definition of ListNode is as follows: 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) {}
};
But i am getting this runtime error: member access within null pointer of type 'ListNode'.但我收到此运行时错误:成员访问类型为“ListNode”的 null 指针。
Am i making some mistake in creating or initialising the node?我在创建或初始化节点时犯了一些错误吗? Please explain.
请解释。
It is unusual for a clone method to return a new list in reverse order, but OK, if that is your actual requirement.克隆方法以相反的顺序返回新列表是不常见的,但是如果这是您的实际要求,那没关系。
As stated in comments, the code you have shown does not account for the possibility of the list being empty (ie, when head
is nullptr
), eg:如评论中所述,您显示的代码不考虑列表为空的可能性(即,当
head
为nullptr
时),例如:
ListNode* cloneList(ListNode* head) {
if (!head) return nullptr; // <-- add this
...
}
If head
is not nullptr
and points to a valid ListNode
, and the list is properly null-terminated, then your code works just fine.如果
head
不是nullptr
并且指向一个有效的ListNode
,并且该列表正确地以 null 终止,那么您的代码就可以正常工作。
However, it can be simplified a bit, eg:但是,它可以简化一点,例如:
ListNode* cloneList(ListNode* head) {
ListNode *newHead = nullptr;
while (head) {
newHead = new ListNode(head->val, newHead);
head = head->next;
}
return newHead;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.