传递给头文件中的函数时,链表的根指针不断变化,如何保持不变?

Root pointer of linked list keeps varying when passed to a function in header file, How to keep it constant?

我创建了一个包含一些基本链表函数的头文件,其中之一是 append(),它以一个 struct node* 指针和值作为参数。 所以当我调用该函数时,由于某种原因根值被更改,所以我不得不继续从被调用函数和 main 传递根指针。 他们有办法纠正这个问题吗?

**我试过的:**

**主要源代码:**

#include"singly_linked_list0.h"

struct node* root = NULL;

int main(){
    int n = 5;
    while(n > 0){
        root = append(root, n);
        n--;
    }
    print_all(root);

    return 0;
}

** 头函数:**

/*appends the value passed at the end, and returns the ROOT*/
struct node* append(struct node* ROOT, int d){
    struct node *temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = d;
    temp->link = NULL;
    if(ROOT == NULL) ROOT = temp;
    else{
        struct node *p;
        p = ROOT;
        while(p->link != NULL){
            p = p->link;
        }
        p->link = temp;
    }

    return ROOT;
}

您可以将指向根指针的指针传递给您的 append 函数:

void append(struct node **ROOT, int d){
    struct node *temp = malloc(sizeof(*temp));

    // Check whether malloc was successful. Otherwise, exit with error
    if (temp == NULL)
        exit(-1);

    temp->data = d;
    temp->link = NULL;

    // If there is no root node yet, this can be set directly
    if (*ROOT == NULL)
        *ROOT = temp;
    // Otherwise, it is not touched
    else {
        struct node *p = *ROOT;
        while(p->link != NULL){
            p = p->link;
        }
        p->link = temp;
    }
}

然后通过 append(&root, n) 调用它。

来源: 正如 P__J__ 提到的,代码中还有一些其他问题已在此处修复。

struct node {int d; struct node *link;} *root = NULL;

struct node* append(struct node* ROOT, int d)
{
    struct node *newnode = malloc(sizeof(*newnode));

    if(newnode)
    {
        newnode -> d = d;
        newnode -> link = NULL;
        if(ROOT)
        {
            struct node *list = ROOT;
            while(list -> link) list = list -> link;
            list -> link = newnode;
        }
        else
        {
            ROOT = newnode;
        }
    }
    return newnode ? ROOT : newnode;
}

void printall(struct node *ROOT)
{
    while(ROOT)
    {
        printf("Node d = %d\n", ROOT -> d);
        ROOT = ROOT -> link;
    }
}

int main()
{
    int n = 5;
    while(n > 0)
    {
        struct node *newroot = append(root, n);
        if(newroot) root = newroot;
        else printf("ERROR at n = %d\n", n);
        n--;
    }
    printall(root);

    return 0;
}

https://godbolt.org/z/jPnhKE