C++ solution, simple and easy to understand


  • 8
    F

    Simply check if the element is duplicate. If yes, record it and use a while loop to go to the next unique element.

    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            ListNode* dummy = new ListNode(0);
            dummy->next = head;
            ListNode* cur = dummy;
            int duplicate;
            while (cur->next && cur->next->next) {
                if (cur->next->val == cur->next->next->val) {
                    duplicate = cur->next->val;
                    while (cur->next && cur->next->val == duplicate) {
                        cur->next = cur->next->next;
                    }
                }
                else {
                    cur = cur->next;
                }
            }
            return dummy->next;
        }
    };

  • 0
    Y

    @Froxie Shall we free(delete) the memory of the duplicate nodes?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.