Insert Node Before Specified Position Linked List C

Insert Node Before Specified Position Linked List C

Following our last tutorial where we insert a node after a certain position, in this one we will learn how to insert node before specified position in a C linked list.

As our previous lessons on this subject, the below function is meant to be used with the linked list example we did in the first tutorial so check it here.

How to insert node before specified position

To do so we must check to things:

  1. That the list is not null.
  2. That the position is valid.
    • This means that we cannot insert before 0 element or after the last one.

The addFirst method you see below was covered here where we talked about adding node to the beginning of a linked list.

struct Person* addBefore(struct Person* list, char* name, int age, int before) {
    if (list != NULL) {
        if (before < 0) {
            //invalid position
            return list;
        } else if (before == 0) {
            list = addFirst(list, name, age);
            return list;
        } else if (before <= (list->listSize - 1)) {
            struct Person* temp = list;
            int i = 0;
            while (temp) {
                if (i == before - 1) {
                temp = temp->next;
            struct Person* originalNextElement = temp->next;
            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;
            temp->next = newPersonNode;
            newPersonNode->next = originalNextElement;
            return list;
        } else {
            //position exceeds last element
            return list;
    } else {
        //list is null
        return NULL;

In the below main() method we create a list with four elements. Then we want to add “jacob” before the 2nd element. This means we want to add jacob before sam.

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 = addBefore(list, "jacob", 49, 2);

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

    return 0;


List size is: 5
mike, age: 23
joe, age: 54
jacob, age: 49
sam, age: 30
john, age: 28