The soution provided for the singly-linked list has an error for deleting the first node (head). The solution provided is:
'''/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
SinglyListNode *cur = getNode(index);
if (cur == NULL) {
return;
}
SinglyListNode *prev = getNode(index - 1);
SinglyListNode *next = cur->next;
if (prev) {
prev->next = next;
} else {
// modify head when deleting the first node.
head = next;
}
}
'''
Since the getNode() method is written as:
'''
SinglyListNode* getNode(int index) {
SinglyListNode *cur = head;
for (int i = 0; i < index && cur; ++i) {
cur = cur->next;
}
return cur;
}
'''
The getNode() fucntion return any index smaller than zero (indexes which are negative) equal the head. In other words, head pointer is always returned when negative indices are assumed as the input.
To resolve this in the line "if (prev) ..." in the deleteAtIndex should write: if (index-1>-1)... . This resolves the bug and the first element will be delete correctly.