繁体   English   中英

C 中的链表实现失败

[英]Failed implementation of a Linked List in C

我不明白为什么这个程序不工作并且元素没有按预期插入到列表中。

每次,当我调试时,我看到当我 go 到'insert'方法之后的main方法时,链接列表仍然是空的,我不明白为什么,因为我认为它应该很好,因为我使用的是指针(这似乎是一个“悬空指针”案例,但如果是,我不明白为什么)。

也许我应该使用双星(**)? 如果是,为什么在 arrays 中没关系?

这是源代码:

#include <stdio.h>
#include <stdlib.h>

struct A{
    int val;
    struct A* next;
} A;

void insert(struct A* L, int newVal) {

    if (L == NULL) {

        L = (struct A*) malloc(sizeof(struct A));
        L->val = newVal;
        L->next = NULL;
    }

    else {

        struct A* p = L;

        while (p->next != NULL) {

            p = p->next;
        }

        p->next = (struct A*) malloc(sizeof(struct A));
        p->next->val = newVal;
        p->next->next = NULL;
    }
}


void printA(struct A* printed) {

    struct A* p = printed;

    while (p != NULL) {
        printf("%d\n", p->val);
        p = p->next;
    }
}


int main() {

    struct A* L = NULL;

    insert(L, 1);
    printf("1 success\n");

    insert(L, 2);
    printf("2 success\n");

    insert(L, 3);
    printf("3 success\n");

    insert(L, 4);
    printf("4 success\n");

    insert(L, 5);
    printf("5 success\n");

    printf("\n\n\n");

    printA(L);

    return 0;
}

谢谢你。

insert function 第一个参数是指向结构的指针。 当你传递你的结构时, insert接收地址,并创建一个指向同一个地方的本地指针。 为了更改实际结构(来自 main)指向的内容,您必须传递一个双指针。

下面写的是需要修改的部分:

void insert(struct A** L, int newVal) {

    if (*L == NULL) {

        *L = (struct A*) malloc(sizeof(struct A));
        (*L)->val = newVal;
        (*L)->next = NULL;
    }

    else {

        struct A* p = *L;

        ...
        ...
        ...
    }
}    

int main() {

    struct A* L = NULL;

    insert(&L, 1);
    printf("1 success\n");

    ...
    ...
    ...

    printA(L);

    return 0;
}

另一种方法是保留单个指针,但将insert的返回值更改为struct A* 您只需将返回值分配给您的结构,如下所示:

struct A *insert(struct A* L, int newVal) {

    if (L == NULL) {

        L = (struct A*) malloc(sizeof(struct A));
        L->val = newVal;
        L->next = NULL;

        return L;
    }

    else {
        ...
    }

    return L;
}

int main() {

    struct A* L = NULL;

    L = insert(L, 1);
    ...
    return 0;
}

此外,您的打印件 function 不会在任何地方移动。 添加行p = p->next;

void printA(struct A* printed) {

    struct A* p = printed;

    while (p != NULL) {
        printf("%d\n", p->val);
        p = p->next;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM