C++ 8ms O(n) solution
/\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode next;\n *     ListNode() : val(0), next(nullptr) {}\n *     Lis
/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* deleteDuplicates(ListNode* head) {\n        if(head==NULL)\n            return head;\n        ListNode*prev=new ListNode(-101);\n        prev->next=head;\n        ListNode*temp=head;\n        ListNode*temp2=new ListNode(-102);\n        ListNode*h=temp2;\n        while(temp->next!=NULL){\n            if(temp->val!=prev->val && temp->val!=temp->next->val){\n                if(temp2->val==-102){\n                      temp2->val=temp->val;\n                    h=temp2;\n                }\n                \n                else{\n                     ListNode*node=new ListNode(temp->val);\n                   temp2->next=node;\n                temp2=node;   \n                }\n              \n            }\n            temp=temp->next;\n            prev=prev->next;\n        }\n           if(temp->val!=prev->val){\n                if(temp2->val==-102){\n                      temp2->val=temp->val;\n                    h=temp2;\n                }\n                \n                else{\n                     ListNode*node=new ListNode(temp->val);\n                   temp2->next=node;\n                temp2=node;   \n                }\n              \n            }\n        temp2->next=NULL;\n        if(h->val==-102)\n            return NULL;\n        return h;\n    }\n};
[]