最后添加节点(C中的结构节点)

时间:2014-12-11 17:04:34

标签: c nodes

list *add_item(list *l, int value){
list *temp;
temp = malloc(sizeof(list));
temp->data = value;
temp->next = l;
l = temp;
return l;}

这是要插入列表前面的代码。我怎么能改变这个?我想在最后插入。谢谢

4 个答案:

答案 0 :(得分:0)

您必须遍历列表直到temp->next == NULL,然后在那里添加节点。如果您不想迭代,可以保留对最后一个元素的last引用。此外,行l = temp什么都不做。

答案 1 :(得分:0)

可能是:

list *add_item(list *l, int value){
list *temp;
temp = malloc(sizeof(list));
temp->data = value;
temp->next = 0;
l->next = temp;
return l;}

如果* l是列表的头部

list *add_item(list *l, int value){
list *temp;
temp = malloc(sizeof(list));
temp->data = value;
temp->next = 0;
list* tmp = l;
while(tmp->next) tmp = tmp->next;
tmp->next = temp;
return l;}

答案 2 :(得分:0)

遍历列表,我假设您在列表末尾指向list->next null。找到该位置并引用新创建的元素。

假设您的头部指向列表的第一个元素

List *temp = head;
List *newElement = malloc(sizeof(List));
List *currNode;
//some assignment 
while(temp!= null )
{
     currNode = temp;
     temp = temp->next;
}
currNode->next = newElement;

答案 3 :(得分:0)

试试这个

list *add_item(list *l, int value) {
    list *head, *temp;
    head = l;
    temp = malloc(sizeof(list));
    temp->data = value;
    temp->next = NULL;
    while(l->next != NULL) {
        l = l->next;
    }
    l->next = temp;
    return head;
}