Insert a node at a specific position in a linked list

  • + 0 comments

    Here is my C++ solution, you can watch the explanation here : https://youtu.be/jCPAp_UIzAs

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) {
        SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
        if(position == 0) {
            newNode->next = llist;
            return newNode;
        }
        SinglyLinkedListNode* curr = llist;
        while(position - 1) {
            position--;
            curr = curr -> next;
        }
        newNode -> next = curr->next;
        curr->next = newNode;
        return llist;
    }