c++打印链表,分段故障

C++ printing linked list , segmentation fault

本文关键字:分段 故障 链表 打印 c++      更新时间:2023-10-16
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";
    }
}

我假设

这一行
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";
}

我看到的一个问题是你将NULL赋值给head

if (head = NULL)必须是if (head == NULL)