I am reversing a doubly linked list. My function for the same is :
Node* Reverse(Node* head)
{
// Complete this function
// Do not write the main method.
Node* temp = new Node();
if ( head == NULL) { return head; }
while ( head != NULL) {
temp = head->next;
head->next = head->prev;
head->prev = temp;
if (temp == NULL ) { break; }
head = temp;
}
return head;
}
This works correctly. Instead of using the break command, if I do 'return head' than the function exits the while loop and has a compile error: control reaches end of non-void function [-Werror=return-type]
Node* Reverse(Node* head)
{
// Complete this function
// Do not write the main method.
Node* temp = new Node();
if ( head == NULL) { return head; }
while ( head != NULL) {
temp = head->next;
head->next = head->prev;
head->prev = temp;
if (temp == NULL ) { return head; }
head = temp;
}
}
What could be the reason behind this?
The reason is that the compiler doesn't know that temp will always end up being NULL at some point, it only knows the loop can end, and the function will have no return statement.
As CompuChip pointed out, you may add the following line at the end, to appease the compiler:
throw std::runtime_error("Control should never reach this point");
Or you may simply return NULL at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With