I was going through the Programming Interviews Exposed book. There’s a code given for inserting an element at the front of linked lists.
bool insertInFront( IntElement **head, int data ){
IntElement *newElem = new IntElement;
if( !newElem ) return false;
newElem->data = data;
*head = newElem;
return true;
}
IMHO this code forgets to update the next pointer of the new element, doesn’t it ? Although I am sure the code is wrong, I just want to confirm my linked list concepts are not horribly wrong.
I believe the code should add the following line at the right place.
newElem->next = *head;
Can someone please just tell me whether I am right or wrong ?
I’m not sure what kind of interview book you’re reading, but this code example is terrible c++.
Yes, you need to point
newElem->nextto the oldheadbefore overwritinghead. Also, there’s no reason to check if newElem is NULL – if it couldn’t be allocated, C++ throws an exception. Also,insertInFrontshould be a member function ofIntElement, andheadshould be a data member.