简体   繁体   中英

Adding to linked-list in C

I'm having some problems with adding to a dynamic linked list. Basically it seems like my first node is overwritten. Here is the code:

struct palNode {
    int number;
    int pointer_index;
    char* solving_array;
    int solved;
    struct palNode* next;
}

And here is my add method:

struct palNode* add_palNode_from_keyboard(struct palNode* head, int num, int pos){
    struct palNode* newnode = (struct palNode*) malloc(1 * sizeof(struct palNode));

    struct palNode* current_node = head;

    if (current_node == NULL)
    {
        head = newnode;
    }
    else 
    {
        while ((*current_node).next != NULL)
        {
            current_node = (*current_node).next;
        }
        (*current_node).next = newnode;
    }

    (*newnode).number = num;
    (*newnode).pointer_index = pos;

    (*newnode).next = NULL;

    printf("Operation completed\n");

    return newnode;
}

And here are my questions: What am I doing wrong? Is there a more correct way of doing it? I have seen other similar questions but I still dont get them

If the list is initially empty, you set head to the new node, however the pointer head is passed by value so changes to it don't appear in the calling function.

You need to pass in address of the head pointer and modify that so that changes appear outside the function:

struct palNode* add_palNode_from_keyboard(struct palNode** head, int num, int pos){
    // no cast needed here, and no need to multiply by 1
    struct palNode* newnode = malloc(sizeof(struct palNode));

    struct palNode* current_node = *head;

    if (current_node == NULL)
    {
        *head = newnode;
    }
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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