+ 1
Question on Linked List Insertion
https://code.sololearn.com/c66AF9zlWFtr I believe the last list should be 5 4 7 3 4 2 1 1 2 3 4 5 But in my code output 5 and 4 are missing. Can anyone explain why is this happening?
3 Respostas
+ 1
All "prev" pointers are null, because you forgot to update the head element to point to the previous one. Just modify your function like this:
void insertAtHead(Node* &head_ref, int new_data){
Node* new_node = new Node();
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = head_ref;
if (head_ref != NULL) {
head_ref -> prev = new_node;
}
head_ref = new_node;
}
+ 1
Martin Taylor thanks for letting me know that. I didn't aware of that.