我正在尝试删除一个按值传递并由函数返回的节点,但头部是按引用传递的。我试过这段代码,但编译器在以下地方提示: *head = *head->next;
代码如下:
#include<stdio.h>
typedef struct nody student;
struct nody{
char name[20];
double gpa;
student *next;
};
student* deletefirstlist(student **head, student *nn);
int main(){
student *head, *node, *w;
node = (student*) malloc(sizeof(student));
gets(node->name);
node->gpa=3.6;
node->next=NULL;
head = node;
node = (student*) malloc(sizeof(student));
gets(node->name);
node->gpa=3.7;
node->next=head;
head = node;
w = head;
while(w!=NULL){
printf("%s %lf\n\n", w->name, w->gpa);
w=w->next;
}
node = deletefirstnode(&head, node);
while(w!=NULL){
printf("%s %lf\n\n", w->name, w->gpa);
w=w->next;
}
return 0;
}
student* deletefirstlist(student **head, student *nn){
nn = *head;
*head = *head->next; // the problem is here
nn->next=NULL;
return nn;
}
感谢一百万
最佳答案
从引用的代码中我了解到您创建了一个带有头和链接节点的列表,然后您尝试删除第一个(头)节点。如果是这样,那么 您的代码必须更正为以下内容:
#include<stdio.h>
typedef struct nody student;
struct nody{
char name[20];
double gpa;
student *next;
};
student *deletefirstnode(student *head, student *nn);
int main(){
student *head, *node, *w;
node = (student*) malloc(sizeof(student));
gets(node->name);
node->gpa=3.6;
node->next=NULL;
head = node;
node = (student*) malloc(sizeof(student));
gets(node->name);
node->gpa=3.7;
head->next=node;
node->next=NULL;
// head->next = node (The first node is the head node)
w = head;
while(w!=NULL){
printf("%s %lf\n\n", w->name, w->gpa);
w=w->next;
}
node = deletefirstnode(head, node);
free(head); //to free up the memory of the old first node
w=node; //reset w to point to the new First node of the list
while(w!=NULL){
printf("%s %lf\n\n", w->name, w->gpa);
w=w->next;
}
return 0;
}
student *deletefirstnode(student *head, student *nn){
nn = head->next;
return nn;
}
希望这些帮助。
关于c - 删除在c中通过引用传递的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40413537/