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 withmalloc
and uses the valuel
that does not exist. Its functionadd_last
returns the list but you do not use it inmain
. 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.– Isac
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
– Fábio Silva
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
– Fábio Silva