Confused About C++ Linked List Quiz Question: Why Is My Answer Wrong?

0
1
Asked By SillyPenguin42 On

I need some help with a quiz question my professor marked wrong. The question involves completing a function called `removeAfter()` in a singly-linked list class in C++. The function checks a few conditions before attempting to remove a node. Here's the relevant part of the code snippet:

```c++
void removeAfter(Node* currentNode) {
if (currentNode == nullptr && head) {
Node* nodeBeingRemoved = head;
head = head->next;
delete nodeBeingRemoved;
if (head == nullptr) {
tail = nullptr;
}
}
else if (currentNode->next) {
Node* nodeBeingRemoved = currentNode->next;
Node* succeedingNode = xxx;
currentNode->next = succeedingNode;
delete nodeBeingRemoved;
if (succeedingNode == nullptr) {
tail = currentNode;
}
}
}
```

I answered with `nodeBeingRemoved->next` for the placeholder `xxx`, but the professor marked it wrong, stating that the correct answer is `currentNode->next->next`. A few of us got it wrong and when we asked the professor for clarification, he couldn't really explain why. Can someone help me understand this? Thanks!

4 Answers

Answered By CaffeineMachine On

Maybe it's a performance issue? Theoretically, `currentNode->next->next` could be handled better by the CPU than `nodeBeingRemoved->next`. Just a thought, though it seems like a long shot.

Answered By CodeGuru123 On

I'd have to say the professor is wrong. But let's think about edge cases — like what happens if both `currentNode` and `head` are `nullptr`? That could lead to issues.

Answered By ConfusedCoder88 On

It looks like the professor might be mistaken. At the point referred to by `xxx`, `nodeBeingRemoved` is already set to `currentNode->next`, which means `nodeBeingRemoved->next` is actually the same as `currentNode->next->next`. So, your answer seems correct to me.

Answered By QuestioningDev On

Honestly, both options seem equivalent in a way. Maybe the professor was just being overly cautious about how the nodes are accessed?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.