为什么我的C++代码在以下打印链表的代码片段中显示分段错误?

Why does my C++ code show segmentation fault in the following snippet of printing a linked list?

本文关键字:代码 片段 显示 分段 错误 打印 C++ 我的 为什么 链表      更新时间:2023-10-16

我有这个问题,我必须编写一个函数来打印完整的链表。您能否解释为什么我会收到此错误以及如何解决它

/*
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;
}
}

您不检查参数头是否为 NULL。如果调用 Print(NULL(,则正在尝试访问空指针,并且可能会发生分段错误。

void Print(Node *head)
{
if(head == nullptr) return;
cout<<"test";
while(head->next!=NULL)
{
cout<<(head->data)<<endl;
head=head->next;
}
}