Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting Element single linked List C

I try to insert an Element in an empty single Linked List and print that.
The code looks like this.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

    typedef struct Node{
    int val;
    struct Node* next;
}ll;

void addElement(ll* List, int num){
ll* new = malloc(sizeof(ll));

if(new == NULL){
printf("NO MEMORY\n");
exit(0);
}

new->val = num;
new->next = NULL;

if(List == NULL){
List = new;
return;
}

ll* curr = List;
while(curr->next != NULL){
curr = curr->next;
}
curr->next = new;
}


void printElements(ll* List){

ll* curr = List;

while(curr != NULL){
printf("%i\n", curr->val);
curr = curr->next;
}
}
*int main(){
ll* list = NULL;
addElement(list, 20);
addElement(list, 30);
addElement(list, 19);
printElements(list);

return 0;*
}

Does anybody see my mistake? Because it only works if i already have an Element in my List and nothing will be printed.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The function deals with a copy of the value of the pointer to the head node used as the function argument.

void addElement(ll* List, int num){

So this statement

List = new;

does not change the value of the original pointer. It changes the value of the copy of the original pointer.

The function can be defined the following way

int addElement( ll **List, int num )
{
    ll *new_node = malloc( sizeof( ll ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->val = num;
        new_node->next = NULL;

        while ( *List != NULL ) List = &( *List )->next;

        *List = new_node;
    }

    return success;
}

And the function is called like

ll* list = NULL;
addElement( &list, 20);
addElement( &list, 30);
addElement( &list, 19);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading