Home:ALL Converter>Remove Duplicates from sorted list not passing all testcases

Remove Duplicates from sorted list not passing all testcases

Ask Time:2018-03-01T10:36:24         Author:crazychecks

Json Formatter

This is a question on leetcode. For some reason my code only works for 7/164 test cases. i would like to know why my algorithm is not efficient. what is a solution to this? what is wrong with my code? here is link to the problem https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/

edit: i have taken suggestions and edited code but my algorithm is still not passing, i am getting a time limit exceed error. is the algorithm efficient?

class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
    ListNode* current = head;
    ListNode* nex;

    while(current!=NULL){
        nex=current->next;
        if (nex==NULL)
            break;


        if(current->val==nex->val)
            current->next=nex->next;
        if (current->next==NULL)
            break;
        current==current->next;
         if(current->next==NULL)
            break;



    }
    return current;

}

};

Author:crazychecks,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/49041766/remove-duplicates-from-sorted-list-not-passing-all-testcases
273K :

nex is not initialized. You try to compare it with NULL before it is initialized.\n\nYou remove duplicates of the neighbor pairs only. It is OK for sorted lists. \n\nYou get into memory leaks.\n\nThe final two if are odd.\n\nI think you return from the function not what is expected.\n\nUsed == where = should be used.\n\nYour should not change current after current->next changed.\n\nwhile (current && (nex = current->next)){\n if (current->val == nex->val) {\n current->next = nex->next;\n delete nex;\n } else {\n current = current->next;\n }\n}\nreturn head;\n",
2018-03-01T02:38:34
yy