Insert a node at a specific position in a linked list

  • + 0 comments

    Sol in C++

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) { SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);

    if(position == 0){
        newNode -> next = llist;
        llist = newNode;
        return llist;
    }else{
        SinglyLinkedListNode* current = llist;
        int i=0;
        while(i<position-1 && current->next!=nullptr){
            current = current->next;
            i++;
        }
        if(current->next == nullptr){
            newNode->next = nullptr;
            current->next = newNode;
        }else{
            newNode -> next = current->next;
            current -> next = newNode;
        }
        return llist;   
    }
    

    }