I am learning CPP (first language) and I am trying to reverse a linked list. this code is not working
node* reverse(node** head){
node* previous=NULL;
node* current=*head;
node* nextptr=current->next;
while(current!=NULL){
current->next=previous;
previous=current;
current=nextptr;
nextptr=nextptr->next;
}
return previous;
}
this one is working
node* reverse(node** head){
node* previous=NULL;
node* current=*head;
node* nextptr;
while(current!=NULL){
nextptr=current->next;
current->next=previous;
previous=current;
current=nextptr;
}
return previous;
}
Why does the second code snippet works while the first one doesn't ?
Why does the second code snippet works while the first one doesn't ?
The first snippet doesn't check before it dereferences potentially null pointers. Because you are using a null pointer to indicate the end of the list, it always dereferences a null pointer, and so has undefined behaviour.
The second snippet never dereferences a pointer it hasn't verified is non-null.