Insert Node after a Certain Position in a Linked List C

Insert Node after a Certain Position in a Linked List C

This lesson shows how you can insert node after a certain position. This means your list must already be populated (non null).

Check the first lesson on the linked list. It contains the rest of code such as list creation, struct definition etc.

Insert Node after a Certain Position

insert_node_after_a_certain_position_in_a_linked_list_C

To insert node after a certain position you must make sure that your linked list:

  • Is not null. This isn’t a method that generates lists. Only modifies it so it must already exist.
  • The insertion can only occur at least after first element and at most after the last one.
  • If position is valid, we iterate the list until we find the node after which we want to insert.
  • We get hold of the regular (current) next element.
  • We create our new node.
  • We make the node we found earlier to point to the newly created one instead of the original next.
  • We make the newly created node to point to the original next.
  • We increase the list size.
struct Person* addAfter(struct Person* list, char* name, int age, int after) {
    if (list != NULL) {
        if (after < 0) {
            //obviously invalid position
            return list;
        } else if (after < (list->listSize)) {
            struct Person* temp = list;
            int i = 0;
            while (temp != NULL) {
                if (i == after)
                    break;
                temp = temp->next;
                i++;
            }
            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;
            list->listSize++;
            return list;
        } else {
            //after position exceeds current list size;
            return list;
        }
    } else {
        return NULL;
    }
}

As usual I made a video explaining the above function.

To test, I want to insert node after a certain position, let’s say… 2. This means after the third element because we respect the zero based numbering.

This means “marvin” should be inserted after 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 = addAfter(list, "marvin", 17, 2);

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

    return 0;
}

Correct!

List size is: 5
mike, age: 23
joe, age: 54
sam, age: 30
marvin, age: 17
john, age: 28
FacebookTwitterLinkedin