Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug in Programming Interviews Exposed?

Tags:

c++

I could not find an errata for the 2nd edition of this book. My question concerns the if-statement in the following piece of code.

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

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

if (*head) { ... }

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

Thanks,

Sam

like image 607
Sam Avatar asked Dec 10 '22 10:12

Sam


2 Answers

The book is a little flawed in that it first claims that there are no problems with *head as an input, and then further develops to say you should really pass in **head, and then says you should check *head. You really need to check *head AND head.

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

like image 165
Jeff Avatar answered Dec 27 '22 22:12

Jeff


The code as shown is incorrect: if *head is null, you dereference it, which is certainly incorrect.

like image 25
James McNellis Avatar answered Dec 28 '22 00:12

James McNellis