【问题标题】:Inserting an element at the end of a linked list?在链表的末尾插入一个元素?
【发布时间】:2016-06-30 03:27:05
【问题描述】:

当传递链表的头部时,这个“在简单链表末尾插入一个元素”的实现有什么问题?

void insert (int x, cel *ini) {
    cel *tmp = ini;
    while (tmp != NULL)
        tmp = tmp->prox;
    cel *new = malloc(sizeof(cel));
    new->value = x;
    tmp->prox = new;
    new->prox = NULL;
}

【问题讨论】:

  • 请提供其余代码以及您遇到的问题。
  • while 循环迭代直到 tmp 为空,然后您尝试取消引用空指针。您必须循环直到 tmp->prox 为空。
  • 您没有检查malloc() 是否成功——这是个问题。如何将第一个元素添加到列表中?
  • 这是一个非常好的教程,@dkb :D

标签: c algorithm linked-list runtime-error


【解决方案1】:

这应该可行:

void insert (int x, cel *ini) {
   cel *tmp = ini;cel *left;
   while (tmp != NULL)
   { 
       left = temp;
       tmp = tmp->prox;
   }
   cel *new =(cel*) malloc(sizeof(cel));
   new->value = x;
   left->prox = new;
   new->prox = NULL;
}

您一直在检查直到tmp 为空,然后添加tmp->prox=new。但问题是当前温度为 NULL。您需要从 temp 的前一个节点指向新节点。

【讨论】:

    【解决方案2】:

    只需将while循环中的条件替换为:

    while(tmp->prox!=NULL)
    

    它可以正常工作,因为您必须到达当前链表的最后一个指向 NULL 的节点。

    但是您需要添加以下条件来检查ini是否为NULL,为此,请在循环之前添加以下

    if(ini==NULL)
    {
    cel *new = malloc(sizeof(cel));
    new->value = x;
    new->prox = NULL;
    ini=new;
     }
    

    你的程序正在做的是达到 NULL (你的程序的 tmp 是 NULL )

    【讨论】:

    • 如果 *ini 为空怎么办?
    • 嗯,是的,您必须为此添加一个单独的条件。我已经对答案进行了必要的更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2020-09-11
    • 2020-11-15
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多