Add Node to Beginning of Linked List in C

Add Node to Beginning of Linked List in C

Following the previous lesson, we will now see how you can add a new node at the beginning of a C linked list. The add node to beginning example we are using in this tutorial uses the linked list made in the first first lesson, so if you haven’t read it already, please check Linked List in C Tutorial.

LinkedList: add node to beginning

Inserting a node at the beginning of a linked list consists of:

  1. Creating the new node.
  2. Assing the list as the next element for the newly created node.
  3. Set list pointer to point to the newly created node.
    • This means the original first node now is the second.
struct Person* addFirst(struct Person* list, char* name, int age) {
    struct Person* newPersonNode = (struct Person*)calloc(1, sizeof(struct Person));
    newPersonNode->name = (char*)calloc(strlen(name) + 1, sizeof(char));
    strcpy(newPersonNode->name, name);
    newPersonNode->age = age;

    if (list == NULL) {
        list = newPersonNode;
        newPersonNode->listSize = 1;
        return newPersonNode;
    } else {
        newPersonNode->next = list;
        newPersonNode->listSize = list->listSize;
        newPersonNode->listSize++;
        list = newPersonNode;
        return list;
    }
}

I also made a short video explaining the above method.

Now in our main() function we use the function to add Bob at the beginning of the list.

int main() {
    struct Person* list = NULL;
    list = addNode(list, "mike", 23);
    list = addNode(list, "joe", 54);
    list = addNode(list, "sam", 30);
    list = addNode(list, "john", 28);
    list = addFirst(list, "bob", 22);

    printf("List size is: %d\n", list->listSize);
    printList(list);

    return 0;
}

The output is:

List size is: 5
bob, age: 22
mike, age: 23
joe, age: 54
sam, age: 30
john, age: 28

Extra tip:
We can rewrite our function to return void.

void insertFirst(struct Person** list, char* name, int age) {
    struct Person* newPersonNode = (struct Person*)calloc(1, sizeof(struct Person));
    newPersonNode->name = (char*)calloc(strlen(name) + 1, sizeof(char));
    strcpy(newPersonNode->name, name);
    newPersonNode->age = age;

    if (*list == NULL) {
        *list = newPersonNode;
        newPersonNode->listSize = 1;
    } else {
        newPersonNode->next = *list;
        newPersonNode->listSize = (*list)->listSize;
        newPersonNode->listSize++;
        *list = newPersonNode;
    }
}

And now we can call this function as:

insertFirst(&list, "bill", 25);

Output:

List size is: 6
bill, age: 25
bob, age: 22
mike, age: 23
joe, age: 54
sam, age: 30
john, age: 28
FacebookTwitterLinkedin