If we don't free the memory allotted to deleted nodes,doesn't it causes memory leaks?


Comment body goes here.


Yes. The object should be deleted and the pointer set to NULL. This is my modification to the while loop in the editorial solution:

while(head->next != NULL && head->val == head->next->val) {
                            ListNode *temp =head->next; //temporarily store duplicate element
                            head->next = head->next->next;
                            delete temp; // delete object
                            temp = NULL; // set pointer to null. I think this one is optional because it was defined inside the loop