Add initial value to a linked list

Asked

Viewed 36 times

0

Good night. I am implementing a linked list and wanted to do a function to add to the bottom of the list an element, in that function I wanted to check if the list is empty and if so add the first element to the list but I am not able to.

Node definition and macros

#define VALUE(p) ((p) -> value)
#define NXT(p) ((p) -> nxt)

typedef struct node{
    int value;
    struct node *nxt;
}NODE;

Creating a new node

    NODE * new_node (int v, NODE *prox){
        NODE *l= (NODE*)malloc(sizeof(NODE));

        VALUE(l)= v;
        NXT(l) = prox;
}

Function to add elements at the end of the list

NODE *add_last(int x, NODE *l){ 

    NODE *curr=l;

    if(l==NULL){
        NODE *aux = new_node(x, l);
        l=aux;
        return l;
    }


    while(NXT(curr)!=NULL){
        curr=NXT(curr);
    }

    NXT(curr)= new_node (x, NULL);
    return l;
}

Main function

int main(){
    NODE *lista=NULL;
    add_last(6, lista);
}

If anyone can help me, I’d appreciate it. Best regards

  • Its function new_node does not create a node with malloc and uses the value l that does not exist. Its function add_last returns the list but you do not use it in main. And the macros you set at the beginning are strange and are not useful because they hide pointer notation that helps you understand the type of each variable in the code.

  • By mistake I had not put the line of the code that uses malloc, already corrected. Regarding macros it was the teacher of the chair who recommended to use. Regarding not using the list in main, that means I have to make list=add_last?. Thanks in advance

  • I’m confused because if I do list=new_node() the calls to add_last work without problem, however I in add_last wanted to create the first element of the list if the list had no elements and that’s what I’m not able to do

1 answer

0


Missing return in node creation function:

NODE * new_node (int v, NODE *prox) {
    NODE *l= (NODE*)malloc(sizeof(NODE));

    VALUE(l)= v;
    NXT(l) = prox;

    return l; //<-- este
}

And in the main missing to use the list that is returned in the function add_last:

int main() {
    NODE *lista=NULL;
    lista = add_last(6, lista);
//  ^^^^^^^
}

Without this your function returns a new list when it is empty, but you do not use it, and so it is as if you have never added it. It would only work properly in case it already had elements.

Watch it work on Ideone

  • Thanks is already working

  • @Fabiosilva No problem, we’re here to help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.