【问题标题】:Add a user generated node to the end of a linked list in C将用户生成的节点添加到 C 中链表的末尾
【发布时间】:2018-10-16 02:55:10
【问题描述】:

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

节点声明:

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;

}

非常感谢任何帮助。


已解决:

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

【问题讨论】:

  • head = NULL 这不是你想要的。
  • 应该改为“==”吗?
  • 确实,= 是一个作业。
  • if(head = NULL) { 表示您没有完全启用编译器警告。 (我希望收到警告)节省时间,启用它们或获取新的编译器。
  • 代码更新为在这种情况下还包括一个中断,因为它也丢失了。

标签: c memory-management linked-list allocation


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2014-02-02
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多