Insert a node at a specific position in a linked list

  • + 0 comments

    C++14

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) 
    {
        SinglyLinkedListNode* newNode = new SinglyLinkedListNode(data);
        
        SinglyLinkedListNode* aux;
        aux = llist;
        
        
        if (position == 0)
        {
            newNode->next = llist;
            llist->next = newNode;    
        }   
        else
        {
            for (int i = 0; i < position - 1; i++) 
            {
                aux = aux->next;
            }
            newNode->next = aux->next;
            aux->next = newNode;
        }
        
        return llist;
    }