Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I am attempting to remove a node with a passed in value from a circular linked list recursively. All data is private so recursive helpper

I am attempting to remove a node with a passed in value from a circular linked list recursively. All data is private so recursive helpper function needed. What's wrong with my code? (some functions omitted for simplicity)
int main(){
CircularLinkedList myList;
myList.insertAtEnd(5);
myList.insertAtEnd(69);
myList.insertAtEnd(89);
std::cout << "Original list: "<< std::endl;
myList.display();
myList.deleteNode(89);
std::cout << "List after deleting node with value 2: ";
myList.display();
return 0;
}
Node* CircularLinkedList::deleteNodeRecursive(Node* current, int value){
if (current == nullptr){
return nullptr;
}
if (current->getData()== value){
Node* temp = current->getNext();
// Check if node to be deleted is the head of the list
if (current == head){
// Update head to the next node
head = temp;
// If the list becomes empty
}
delete current;
return temp;
}
// Set the next pointer of the current node to the result of the recursive call
//current->setNext(deleteNodeRecursive(current->getNext(), value));
// Same as above but in steps:
Node* nextNode = current->getNext(); // Step 1
Node* updatedNextNode = deleteNodeRecursive(nextNode, value); // Step 2
current->setNext(updatedNextNode); // Step 3
return current;
}
void CircularLinkedList::deleteNode(int value){
if (head != nullptr){
head = deleteNodeRecursive(head, value);
if (head == nullptr){
std::cout << "Value "<< value <<" not found in the list." << std::endl;
} else {
std::cout << "Node with value "<< value <<" deleted." << std::endl;
}
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Concepts

Authors: David Kroenke, David Auer, Scott Vandenberg, Robert Yoder

9th Edition

0135188148, 978-0135188149, 9781642087611

More Books

Students also viewed these Databases questions