c - 删除在c中通过引用传递的节点

标签 c linked-list

我正在尝试删除一个按值传递并由函数返回的节点,但头部是按引用传递的。我试过这段代码,但编译器在以下地方提示: *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/

相关文章:

c - AVL/二叉搜索树

c - 为什么这段代码不起作用?

c++ - C++ 中的链表、多项式、重载运算符 << 和 >>

c - Getop 函数负数

C编程读取文件并将其存储为字符串

java - 如何使用HashMap在恒定时间内从Java的LinkedList中获取元素

java - LinkedList 的简单 Java 排行榜

c - 删除链表头后出现垃圾打印

linked-list - 用尾指针编写链表的惯用方法是什么?

c - 守护进程被杀死时会自行清理