在链表的末尾插入一个元素?

时间:2016-06-30 03:27:05

标签: c algorithm linked-list runtime-error

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

new myObj

2 个答案:

答案 0 :(得分:2)

这应该有效:

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。但问题是当前的temp是NULL。您需要从上一个temp节点指向新节点。

答案 1 :(得分:0)

只需将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)