c - 将用户生成的节点添加到 C 中链表的末尾

标签 c memory-management linked-list allocation

我认为我搞砸了一些我没有看到的简单事情,但应该发生的是选择了添加新节点的菜单选项。主程序创建一个新节点,将其传递给一个函数,将其添加到链表的末尾。下面的代码片段应该有助于解释我所做的事情。

节点声明:

typedef struct Node {
    char fname[51];
    char lname[51];
    int idnum;
    float scores[5];
    float average;

    struct Node *next;
} Node;

新节点创建和用户分配的值:

 case 'A':
     entry = (Node*)malloc(sizeof(Node));
     printf("Enter the name of the record you would like to append\nFirst:");
     scanf("%50s", &(*entry).fname);
     printf("\nLast:\n");
     scanf(" %50s", &(*entry).lname);
     printf("Enter the ID of the record you would like to append\n");
     scanf("%d", &(*entry).idnum);
     printf("Enter the scores of the record you would like to append\n");
     for(j=0;j<5;j++) {
         scanf("%f", &(*entry).scores[j]);
     }
     head = addend(head,entry);
     printrecords(head,disp);
break;

将节点添加到链表末尾:

Node* addend(Node* head, Node* entry) {
    if(head == NULL) {
            return NULL;
    }

    Node *cursor = head;
    while(cursor->next != NULL) {
            cursor = cursor->next;
    }
    cursor->next = entry;

    return head;

}

非常感谢任何帮助。

<小时/>

已解决:

不知道为什么当我传递要分配给它的节点时要创建一个新节点。更新代码以反射(reflect)这一点。另外,正如 @jose_Fonte 指出的那样,在正式环境中使用此代码是有风险的,因为对 head 的引用可能会丢失。

最佳答案

您不应该将一个项目添加到单个链接列表的末尾。它破坏了该结构所基于的添加/删除操作的 O(1) 复杂性的整个想法。它意味着从前面或在您保存节点指针的项目之后增长。因此,我会编写带有两个参数的 add_after 方法:一个指向插入新节点后的节点的指针和一个指向新节点的指针。您可以保留指向新节点的指针并按顺序使用它,以从其背面增长链表。

关于c - 将用户生成的节点添加到 C 中链表的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50194922/

相关文章:

c - 我认为我超出了此过程的可用内存。有人可以看一下并验证吗?

java - 如何从 CSV 数据的第二行开始扫描到链接列表?

c - 将元素添加到有序链接列表

c - 将 char* 中的字符替换为 double 值

c - 需要 __alignof__ 的调试符号

对有效的类型规则感到困惑

java - 如何显示 LinkedList 的所有内容?

c++ - 从 WinAPI 线程调用 omp_set_num_threads 时出现问题

Linux - 在内核代码中映射用户空间内存

java - 文字的字符串分配