2013-08-18 89 views
0

我正在用C++编写一个函数来将“int”类型的“数据”添加到链表的末尾。C++中链接列表实现中的分段错误

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->下一=(节点*)malloc的(的sizeof(节点)),我得到访问冲突错误(分段错误)。我没有发现任何根本错误。你可以在这个问题上给我启发吗?

+0

它不进入循环。而是一个新的节点被初始化,它被temp指向。我的主要链表是“list”,所以实际上我需要给出一个声明:list = temp;在函数结束时。 –

回答

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

上面的代码让你到列表中的最后一个节点。因此,您应该将节点添加到temp本身,而不是temp->next

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

现在最后一个节点的子节点应该是NULL。

temp->next = NULL; 
+1

这个新的'temp'将没有连接到列表,所以为什么要打扰循环? – Beta

+0

我在这里有一个疑问.. temp-> next给出下一个节点的地址。那么新节点应该由temp-> next引用而不是temp? –

+0

此外,'temp'指向最近分配的内存区域。你确定你想把它当作一个'node'吗?使用C++方法有真正的优势。 – Beta

0

就在该行执行之前,temp将为空。然后,您将其解除引用。

1

如果你想获得列表的最后一个节点,只是检查是否下一个成员为空或不作为最后一个节点的下一个成员为空。

在你的代码中,你检查temp为空或不是temp-> next

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

当循环结束时将得到temp为空。

此外,您还应该考虑头部为空的情况。

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; 
    } 

} 
+1

'if(temp!= NULL)'没有帮助 –

+0

我刚刚没注意到。我认为我没有考虑头部无效的情况,你的意思是? – ningyuwhut

+0

是的,看起来你现在已经处理了。 +1 –