0

I am designing a linked list and one of the functions is writing a function that will add a new value to the head of a linked list:

void myLinkedListAddAtHead(MyLinkedList* obj, int val)
{
    MyLinkedList *new, *temp;

    if (obj->n == 0)
        obj->n = val;
    else
    {
        new = malloc(sizeof(MyLinkedList));
        if (new == NULL)
            return;
        new->n = val;
        new->next = obj;
    }
}

I have used a default value of 0, to signify that a list is empty but when the list is not empty it does not work as expected. For example:

myLinkedListAddAtHead(head, 1); //first call to the function
myLinkedListAddAtHead(head, 2); //second call to the function

Output:

1

Why is this happening? I understand that it is the way I implemented the list(I know I can use a double pointer and pass the address of the head node, but still this behavior of pointers is hard to understand easily.

Leuel Asfaw
  • 316
  • 1
  • 14

0 Answers0