C ++打印链表,分段错误
C++ printing linked list , segmentation fault
void Print(Node *head)
{
if (head = NULL)
{
cout << "NULL";
}
else
{
cout << head->data << endl;
head = head->next;
while (head->next != NULL)
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
}
}
我看到的一个问题是您将 NULL 分配给了 head
if (head = NULL)
必须是 if (head == NULL)
我假设这条线
if ( head = NULL )
转录您的代码时出错,您的工作代码使用
if ( head == NULL )
我看到的真正错误是您正在使用
cout << head->data << endl;
head = head->next;
while (head->next != NULL) // This line is not good
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
那条线永远是个问题。在某些时候,head
将等于 NULL
,您将尝试访问 NULL
指针。
将该代码块更改为:
while (head != NULL)
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
其实整个函数可以是:
void Print(Node* head)
{
while (head != NULL)
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
}
void Print(Node *head)
{
if (head = NULL)
{
cout << "NULL";
}
else
{
cout << head->data << endl;
head = head->next;
while (head->next != NULL)
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
}
}
我看到的一个问题是您将 NULL 分配给了 head
if (head = NULL)
必须是 if (head == NULL)
我假设这条线
if ( head = NULL )
转录您的代码时出错,您的工作代码使用
if ( head == NULL )
我看到的真正错误是您正在使用
cout << head->data << endl;
head = head->next;
while (head->next != NULL) // This line is not good
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
那条线永远是个问题。在某些时候,head
将等于 NULL
,您将尝试访问 NULL
指针。
将该代码块更改为:
while (head != NULL)
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
其实整个函数可以是:
void Print(Node* head)
{
while (head != NULL)
{
cout << head->data << endl;
head = head->next;
}
cout << "NULL";
}