这是我在末尾插入节点的linkedlistcode。我收到错误代码转储。所以请帮我解释代码有什么问题。
如果我继续回来;在* headRef = newnode之后的最后一行;它的工作。那么为什么要返回一个无效函数呢。
struct node
{
int data; // node format
struct node* next;
};
void insertAtEnd(struct node** headRef, int newData)
{
struct node* ptr;
struct node* newnode;
ptr = (*headRef);
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = newData;
newnode->next = NULL;
if (*headRef == NULL)
{
*headRef = newnode;
}
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = newnode;
}
答案 0 :(得分:0)
你应该返回内部,因为在if语句之后它再次进入while循环并在末尾添加额外的节点
struct node
{
int data; // node format
struct node* next;
};
void insertAtEnd(struct node** headRef, int newData)
{
struct node* ptr;
struct node* newnode;
ptr = (*headRef);
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = newData;
newnode->next = NULL;
if (*headRef == NULL)
{
*headRef = newnode;
return;
}
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = newnode;
return;
}