首页 > 解决方案 > C链表不能在开头添加元素

问题描述

我对C相当陌生,我们有一个excersie,我们需要用预定的函数和参数编写一个链表。现在我在列表的开头添加一个新元素时遇到了问题,其他一切正常,这里是语法。

int main(){

    Vector3D foo;
    foo.x = 521;
    foo.y = 2;
    foo.z = 3;

    VectorList * head;
    head = create_VL(NULL, &foo);

    insertElementBack(head, &foo);
    foo.x = 456;
    insertElementBack(head, &foo);
    foo.x = 2;
    insertElementFront(head, &foo);
    print_list(head);
    printf("%d\n", size(head));

}

void insertElementFront(VectorList* l, Vector3D* v){

    VectorList *previous, *new_VL;

    previous = &l;

    new_VL = NULL;
    new_VL = malloc(sizeof(VectorList));

    new_VL -> value = *v;

    new_VL -> next = previous;

    l = new_VL;
}

VectorList *create_VL(VectorList* l, Vector3D* v) {

    VectorList* new_VL = (VectorList*)malloc(sizeof(VectorList));

    if(new_VL == NULL)
    {
        printf("Error creating a new node.\n");
        exit(0);
    }
    new_VL->value = *v;
    new_VL->next = l;

    return new_VL;
}

void insertElementBack(VectorList* l, Vector3D* v){

    VectorList *vl = l;

    while( vl -> next != NULL){
        vl = vl -> next;
    }

    VectorList *new_List = create_VL(NULL, v);
    vl -> next  = new_List;

}

名称和参数不允许更改,我可以使用双指针作为参数解决此问题,但不允许更改。有人可以给我一个提示,我尝试了很多东西,但没有任何效果。

最好的

马丁

标签: cpointers

解决方案


你真的应该包括定义VectorList而不是让我们猜测它的结构,但你的问题可能是这样的:

previous = &l;

l是指向 a 的指针VectorList。通过这样做&l,您正在获取指针的地址,而不是VectorList. 所以当你这样做时

new_VL -> next = previous;

您的next指针现在指向该指针,而不是VectorList. 事实上,你没有收到警告吗?不要忽视警告。

您的第二个也是更大的问题是head没有更新以反映新的头,并且无法使用双指针,您唯一的解决方法是将新的头节点作为返回值从insertElementFront.


推荐阅读