C ++中链表实现中的分段错误

问题描述 投票:0回答:4

我正在用C ++编写一个函数,将“int”类型的“数据”添加到链表的末尾。

void insert_back()
{
 int no;
 node *temp;
 cout<<"\nEnter the number"<<"\n";
 cin>>no;
 temp = head;
 if(temp != NULL)
 {
         while(temp != NULL)
                    temp = temp->next;
 }

 temp->next = (node*)malloc(sizeof(node));
 temp = temp->next;
 temp->data = no;
 temp->next = NULL;

}

但是,在行,temp-> next =(node *)malloc(sizeof(node)),我得到一个访问冲突错误(分段错误)。我没有发现任何根本错误。你能否就这个问题赐教我?

c++ segmentation-fault access-violation
4个回答
1
投票

如果要获取列表的最后一个节点,只需检查下一个成员是否为null,因为最后一个节点的下一个成员为null。

在您的代码中,您检查temp是否为null而不是temp-> next。

while(temp != NULL)
    temp = temp->next;

循环结束时,temp将为null。

此外,您还应该考虑头部为空的条件。

void insert_back()
{
    int no;
    node *temp;
    cout<<"\nEnter the number"<<"\n";
    cin>>no;
    temp = head;
    if(temp != NULL)
    {
        while(temp->next != NULL)
            temp = temp->next;
        temp->next = (node*)malloc(sizeof(node));
        temp = temp->next;
        temp->data = no;
        temp->next = NULL;
    }else{
        head = (node*)malloc(sizeof(node));
        head->data = no;
        head->next = NULL;
    }

}

0
投票

就在该行执行之前,temp将为null。然后你取消引用它。


0
投票

您引用的临时值不存在,temp为NULL。要更正此问题,请使用temp-> next!= NULL,而不是在while循环条件中使用temp!= NULL。

 while(temp->next!=NULL)
{
   temp = temp->next;
}

Node* new_node = (Node*)malloc(sizeof(Node));

new_node->data = no;
new_node->next = NULL;
temp->next = new_node;

-1
投票
while(temp != NULL)
    temp = temp->next;

上面的代码将您带到列表中的最后一个节点。所以,你假设将节点添加到temp本身而不是temp->next

temp = (node*)malloc(sizeof(node));

现在,最后一个节点的子节点应为NULL。

temp->next = NULL;
© www.soinside.com 2019 - 2024. All rights reserved.