Insert a node at a specific position in a linked list

  • + 0 comments

    c++

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

    if (position == 0) {
        newNode->next = llist;
        return newNode;
    }
    
    SinglyLinkedListNode* temp = llist;
    while (--position > 0 && temp->next) {
        temp = temp->next;
    }
    
    SinglyLinkedListNode* tempNext = temp->next;
    temp->next = newNode;
    newNode->next = tempNext;
    
    return llist;
    

    }