我有这个问题,我必须编写一个函数来打印完整的链表。你能解释一下为什么我会收到这个错误以及如何修复它
/*
Print elements of a linked list on console
head pointer input could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
void Print(Node *head)
{
cout<<"test";
while(head->next!=NULL)
{
cout<<(head->data)<<endl;
head=head->next;
}
}
答案 0 :(得分:0)
您不检查参数头是否为NULL。如果调用Print(NULL),则尝试访问nullpointer,可能会发生分段错误。
void Print(Node *head)
{
if(head == nullptr) return;
cout<<"test";
while(head->next!=NULL)
{
cout<<(head->data)<<endl;
head=head->next;
}
}