C 链表追加函数在开头添加一个额外的空节点
这就是到目前为止我从链表开始所拥有的。我试图使它,以便我可以附加到多个链表的功能。因此,我只需在main中创建一个不同的根指针,并使用它作为参数调用append函数来添加节点 这似乎是可行的,但是,它在列表的开头添加了一个额外的空节点。此节点不包含任何数据。例如,如果我向列表中添加4个学生,nodeLength函数将返回5。更改此项:C 链表追加函数在开头添加一个额外的空节点,c,linked-list,C,Linked List,这就是到目前为止我从链表开始所拥有的。我试图使它,以便我可以附加到多个链表的功能。因此,我只需在main中创建一个不同的根指针,并使用它作为参数调用append函数来添加节点 这似乎是可行的,但是,它在列表的开头添加了一个额外的空节点。此节点不包含任何数据。例如,如果我向列表中添加4个学生,nodeLength函数将返回5。更改此项: struct node{ char name[50]; double g
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;
}
为此:
void append(struct node* root)
这样,即使append()
终止,您也可以持续进行更改
当然,您必须在该函数体中使用*root
,而不是root
附言:没有 检查此代码以了解一点。我会解释更多 并且不要强制转换
malloc
的返回类型
如果您将参数正确地更改为
struct node**
,那么您所做的工作将很好,但是可以像这样更容易地完成(上面显示的示例)。它比使用双指针更自然、更直观 请在启用警告的情况下编译。例如,您将&root
从main
传递给一个函数,该函数需要一个struct节点*
,而不是struct节点**
。是的,这是一个警告。注意:应为“struct node*”,但参数的类型为“struct node**”。如果只传递“root”,则不会添加节点。length函数返回0。这是一个警告,实际上应该是一个错误。添加节点时,必须能够更新根,因此append(&root)
是正确的,但是您的函数应该是void append(结构节点**根)
。你必须在该函数中使用*root
而不仅仅是root
。它现在可以工作了。谢谢。你的缩进到处都是。请解决这个问题….:他们真的只需要知道答案就可以了。不管怎样,复杂都没关系。反正我不知道该说什么。让人泄气。是的@coderredoc,顺便说一句你贴在那里的答案很好。不,你的答案也很好。但你告诉我这里几乎不需要2个指针。不是吗?单级间接寻址可以实现很多事情。你的答案被选中是因为它引起的变化最小,所以是的,它很有帮助,但只是说。这两种方法都是有效的@codererdoc,这就是为什么我高估了你!=)是的谢谢你。我从你那里学到了一些东西。祝你一切顺利。
void append(struct node** root)
struct node{
char name[50];
double grade;
struct node* next;
};
struct node * 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;
root=iterate;
}
n--;
}
return root; }
int nodeLength(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;
root= append(root);
//printList(&root);
printf("Node length: %d",nodeLength(root));
return 0;
}