簡體   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