We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Here is my code in C++ that passed all the tests !
Node*InsertNth(Node*head,intdata,intposition){Node*temp=head;if(head==nullptr){// create a new nodeNode*mynode=newNode;mynode->data=data;mynode->next=nullptr;head=mynode;returnhead;}else{//count the number of nodesintcount=0;while(temp!=nullptr){++count;temp=temp->next;}if(position==0){Node*mynode=newNode;mynode->data=data;mynode->next=head;head=mynode;returnhead;}elseif(position>=count){// got to the last nodetemp=head;while(temp->next!=nullptr){temp=temp->next;}Node*mynode=newNode;mynode->data=data;mynode->next=nullptr;temp->next=mynode;returnhead;}else{temp=head;intpos=0;while(temp->next!=nullptr&&pos<position-1){++pos;temp=temp->next;}Node*mynode=newNode;mynode->data=data;mynode->next=temp->next;temp->next=mynode;returnhead;}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Insert a node at a specific position in a linked list
You are viewing a single comment's thread. Return to all comments →
Here is my code in C++ that passed all the tests !