Error in Interview Programming?

I could not find a mistake for the second edition of this book. My question is about the if statement in the following code snippet.

void removeHead (Node ** head) { Node * temp; if (!(*head)) { temp = (*head)->next; delete *head; *head = temp; } } 

So, I understand that the if-statement point is to check if Node is null. However, adding an extra "!" to evaluation, doesn't this negate the false null value? It would be correct to change it to something like:

 if (*head) { ... } 

Also, if anyone knows where I can find the official mistake for the 2nd edition, that would be great.

Thanks,

Sam

+4
source share
6 answers

The book is a little flawed in that it first claims that there is no problem with *head as input, and then develops to say that you really have to go to **head , and then says that you should check *head . You really need to check *head And head .

As for if (!(*head)) , if *head is NULL, it will be if (!0) , which would be true. Then we try (0)->next and die. Definitely a mistake.

+9
source

The code, as shown, is incorrect: if *head is null, you will look for it, which is certainly not true.

+2
source

head , which is a pointer to a pointer to Node, you need to not only check that the second-level pointer is not null, but also that the first-level pointer is not null, which you could do by adding the condition head != NULL .

Also, as you correctly pointed out in your comment, the condition !(*head) is actually the opposite of what you want to do (this will be true when *head is NULL). Use rather *head != NULL , more readable and less error prone.

+2
source

Doubt, Is NULL equal to zero regardless of platform ???

I doubt the comparison should always be accepted

 if( * head != NULL ) { ... } 
+1
source

* * head → * head-> head . And when you do this, *head , you play the middle position. And when it's NULL, an if loop is introduced. So, if it is NULL, how can it point to head and request the next member variable. This should work as you said -

 if((*head) != NULL ) { // ... } 
0
source

Get rid of!

Then change delete to free and retag C

0
source

Source: https://habr.com/ru/post/1341768/


All Articles