gpt4 book ai didi

c - 链表附加函数在开头添加一个额外的空节点

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:36 25 4
gpt4 key购买 nike

            struct node{

char name[50];
double grade;
struct node* next;


};





void append(struct node* root){

int n;

printf("Enter the number of students: ");
scanf("%d",&n);

while(n !=0){

struct node* temp;

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

printf("\nEnter the name of the student: ");
scanf("%s",&temp->name);
printf("\nEnter the grade for the student named %s: ",temp->name);
scanf("%f",&temp->grade);
temp->next=NULL;

if(root==NULL){
root=temp;
}else{
struct node* iterate=root;

while(iterate->next != NULL){

iterate=iterate->next;
}

iterate->next=temp;

}

n--;
}


}

int listLength(struct node* root){

struct node* temp = root;
int counter=0;

while(temp !=NULL){

counter++;
temp=temp->next;
}

return counter;

}

int main()
{
struct node* root = NULL;

append(&root);
//printList(&root);
printf("Node length: %d",listLength(&root));
return 0;
}

这是我刚开始使用链表时所拥有的。我试图做到这一点,以便我可以使用该函数附加到多个链表。所以我只是在 main 中创建一个不同的根指针,并将它作为参数调用 append 函数来添加节点。

这似乎可行,但是,它在列表的开头添加了一个额外的空节点。该节点不包含任何数据。因此,例如,如果我将 4 个学生添加到列表中,nodeLength 函数将返回 5。

最佳答案

改变这个:

void append(struct node* root)

为此:

void append(struct node** root)

这样即使 append() 终止,您的更改也能持续。

当然,您必须在该函数体内使用 *root 而不是 root


附言:Do I cast the result of malloc?没有。

关于c - 链表附加函数在开头添加一个额外的空节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com