Home > Software design >  Inserting Element single linked List C
Inserting Element single linked List C

Time:03-09

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.

CodePudding user response:

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);
  • Related