Question: I have these instructions: void remove ( const int index ) . This method accepts an integer. The method should then traverse to and delete

I have these instructions: void remove(const int index). This method accepts an integer. The method should then traverse to and
delete the kth node in the list. This is zero based. Make sure to handle all scenarios (empty list, one node, first
node, last node, and the general scenario). Here is the code I've written, but it is not working correctly: //Remove
template
void DoublyLinkedList::remove(const int index){
if (index <0){
throw std::out_of_range("Error: Invalid index for removal.");
}
if (!this->head){
// Empty list
throw std::out_of_range("Error: Cannot remove from an empty list.");
}
Node* temp = nullptr;
if (index ==0){
// Removing the first node
temp = this->head;
this->head = this->head->next;
if (this->head){
this->head->prev = nullptr;
} else {
// If the list becomes empty after removal, update the tail
this->tail = nullptr;
}
} else {
Node* currentNode = this->head;
int currentIndex =0;
while (currentNode && currentIndex < index){
currentNode = currentNode->next;
currentIndex++;
}
if (!currentNode){
throw std::out_of_range("Error: Index out of bounds.");
}
temp = currentNode;
if (currentNode->next){
currentNode->next->prev = currentNode->prev;
} else {
// If removing the last node, update the tail
this->tail = currentNode->prev;
}
currentNode->prev->next = currentNode->next;
}
delete temp;
}. It is failing this test: //Test deleting a Kth element that doesn't exist.
d->remove(500);
checkTest(testNum++, correct, "1213", d->getListAsString()); //13
checkTest(testNum++, correct, "1312", d->getListBackwardsAsString()); //14. Thanks for any help.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!