C++, 8ms, iterative, naive but easy to implement
It is my first post ever... Did not saw similar ones so I would like to share a naive way to implement this.\nIdea is to set a flag, which indicates the current
It is my first post ever... Did not saw similar ones so I would like to share a naive way to implement this.\nIdea is to set a flag, which indicates the current head should be added or not.\n\n    class Solution {\n    public:\n        ListNode* deleteDuplicates(ListNode* head) {\n            if(!head||!head->next) return head;\n            ListNode* dummy = new ListNode(0);\n            ListNode* tail = dummy;\n            int flag = true; // should the current head be added ?\n            while(head){\n                while(head&&head->next&&head->val==head->next->val)\n                {\n                    flag = false; // finds duplicate, set it to false\n                    head = head->next;\n                }\n                if(flag) // if should be added\n                {\n                    tail->next = head;\n                    tail = tail->next;\n                }\n                head = head->next;\n                flag = true; // time for a new head value, set flag back to true\n            }\n            tail->next = nullptr; // Don't forget this... I did..\n            return dummy->next;\n        }\n    };
['C++']