Insert a node at a specific position in a linked list

  • + 0 comments

    My C solution. ` SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* llist, int data, int position) { SinglyLinkedListNode *newNode = malloc(sizeof(SinglyLinkedListNode *));

    newNode->data = data;
    
    if (llist == NULL) {
        return newNode;
    }
    SinglyLinkedListNode *current = llist;
    SinglyLinkedListNode *temp = malloc(sizeof(SinglyLinkedListNode *));
    
    //temp->data = data;
    for (int i = 0; i < position - 1; i++) {
        current = current->next;
    }
    temp = current->next;
    current->next = newNode;
    newNode->next = temp;
    
    return llist;
    

    } `