将指针传递到链表时出现分段错误

问题描述

各位程序员,下面的代码给出了分段错误。此代码旨在在链接列表的末尾插入元素。我尝试使用打印语句对其进行调试。我认为错误在于将链接列表指针传递给insert()函数。请告诉我如何纠正它。预先感谢。

下面是代码:

#include <iostream>
using namespace std;

class node {
public:
    int data;
    node *next;
    node(int data) {
        this->data = data;
        this->next = NULL;
    } 
};

class linked_list {
public: 
    node *head;
    linked_list() {
        this->head = NULL;
    }
};

void insert(node **head,int data);
void print(linked_list *L);

int main() {
    int N;
    linked_list *A = new linked_list();
    
    cout << "N: ";
    cin >> N;
    for(int i=0; i<=N-1; i++) {
        int t;
        cin >> t;
        insert(&(A->head),t);
    }
    print(A);
    return 0;
}

void insert(node **head,int data) {
    node *temp = new node(data);
    if(*head == NULL) {
        *head = temp;
        return;
    } else {
        node *t = *head;
        while(t->next != NULL) {
            t=t->next;
        }
        t->next = temp;
        return;
    }
}

void print(linked_list *L) {
    node * t = L->head;
    while(t!=NULL) {
        cout << t->data << " ";
        t = t->next;
    }
    return;
}

解决方法

main.cpp:42:14: error: using the result of an assignment as a
      condition without parentheses [-Werror,-Wparentheses]
    if(*head = NULL) {
       ~~~~~~^~~~~~
main.cpp:42:14: note: place parentheses around the assignment to
      silence this warning
    if(*head = NULL) {
             ^
       (           )
main.cpp:42:14: note: use '==' to turn this assignment into an
      equality comparison
    if(*head = NULL) {
             ^
             ==
1 error generated.

您在打算进行比较的地方使用作业。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...