Insert a node at a specific position in a linked list

 https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem

 

SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int p) {
SinglyLinkedListNode* temp=head;
SinglyLinkedListNode* prev=head;
SinglyLinkedListNode* node=new SinglyLinkedListNode(data);
if(head==NULL)return node;
if(p==1){
    node -> next= head;
    return node;
}
else{
    while(p--)
    {
        prev=temp;
        temp=temp->next;
    }
    prev->next=node;
    node->next=temp;
}
return head;
}

 

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!