+ 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?

30th Oct 2021, 4:14 PM
Kashyap Kumar
Kashyap Kumar - avatar
2 ответов
+ 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; }
31st Oct 2021, 10:30 PM
Vasile Eftodii
Vasile Eftodii - avatar
+ 1
Martin Taylor thanks for letting me know that. I didn't aware of that.
2nd Nov 2021, 11:04 AM
Kashyap Kumar
Kashyap Kumar - avatar