Insert a node at a specific position in a linked list

  • + 0 comments

    i were rewite your code

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { SinglyLinkedListNode *newNode,currentNode=head; newNode = (SinglyLinkedListNode)malloc(sizeof(SinglyLinkedListNode)); newNode->data = data;

    if (head == NULL) {
        return newNode;
    }
    
    if (position == 0) {
       newNode->next = head;
       return newNode;
    }
    
    currentNode = head;
    while (position - 1 > 0) {
        currentNode = currentNode->next;
        position--;
    }
    
    newNode->next = currentNode->next;
    currentNode->next = newNode;
    
    return head;
    

    }