试图附加到链表时出现分段错误,c++



我有一个这样定义的结构:

struct Node { 
int day = 0; 
int number = 0;
Node* next = nullptr; 
};

并编写了一个创建函数

Node* ll_create(int day, int number){
Node* p = new Node;
p->day = day;
p->number = number;
p->next = nullptr; 
return p;
}

但我的附加函数总是以分段错误告终

void ll_append(Node* head, int day, int num, int len){
Node* new_cnode = ll_create(day,num);
Node* last = head;
while (last->next != nullptr)
last = last->next;
last->next = new_cnode;
}

有人能告诉我怎么修吗?

问题的根本原因很可能是missing error handling。即,可以遵循一条基本规则:在取消引用任何指针之前,都应该对其进行验证。

void ll_append(Node* head, int day, int num, int len){
Node* new_cnode = ll_create(day,num);
Node* last = head;
while (last->next != nullptr) //Here, last (i.e. head) can be nullptr.
last = last->next;
last->next = new_cnode;
}

可以决定是ll_append的呼叫者应确保head还是ll_append本身可以验证。

第一个解决方案可能如下所示:

void ll_append(Node*& head, int day, int num, int len){
Node* new_cnode = ll_create(day,num);
//Case 1 : When head is pointing to empty list, you can create the first node.
if(not head)
{
head = new_node;
return;
}
//Case 2 : When head is pointing to a valid list (i.e. at least one node is present)
Node* last = head;
while (last->next != nullptr)
last = last->next;
last->next = new_cnode;
}

相关内容

  • 没有找到相关文章

最新更新