In: Computer Science
How do I remove a node from a linked list C++?
void LinkedList::Remove(int offset){
shared_ptr<node> cursor(top_ptr_);
shared_ptr<node> temp(new node);
if(cursor == NULL) {
temp = cursor-> next;
cursor= temp;
if (temp = NULL) {
temp->next = NULL;
}
}
else if (cursor-> next != NULL) {
temp = cursor->next->next;
cursor-> next = temp;
if (temp != NULL) {
temp->next = cursor;
}
}
}
Please find the updated function below , which removes the node
void LinkedList::Remove(int offset){ //Take the offset
shared_ptr<node> cursor(top_ptr_); // first pointer which will reach the offset
shared_ptr<node> temp(top_ptr_); //Temp pointer which will be behind the offset
int count = 1; // count to match the offset
while(cursor->next ! = NULL){ //iterate entire list
if(cnt == offset){ // if we find the offset
temp->next = cursor ->next; //assign the temp of next to cursor of next(if its 1st node still it wil work)
delete(cursor); // detele the main node;
cout<<" Node removed successfully"<<endl;
return ; // retun from the function
}else{
temp = cursor; // set temp to cursor
cursor = cursor ->next; // move cursor to next node
cnt++; //increase the count
}
//if we are out of the loop means we have iterated all the list then we have not found offset
cout<<"The off set entred is less than or greater than the length of list, please enter correct offset"<<endl;
return;
}
i have clearly explained each line of the code, it quite straight forward.
Thanks , still if you have any doubt please post a comment.