Sharing my C++ code with some explanation, easy to understand (at least I think so)


  • 0
    M
       class Solution {
            public:
                ListNode* deleteDuplicates(ListNode* head) {
                    if(!head || !head->next) return head;
                    ListNode **pp = &head;
                    int val =  head->val;
                    bool dup = false;
            
                    while((*pp)->next){
                        if(val == ((*pp)->next)->val){
                            //delete the next node
                            (*pp)->next = (*pp)->next->next;
                            dup = true;
                        }else{
                            if(dup){
                                // delete current node
                                *pp = (*pp)->next;
                                val = (*pp)->val;
                                dup = false;
                            }else{
                               // point to next node
                               pp = &((*pp)->next);
                               val = (*pp)->val;
                            }
                        }
                    }
                    
                    // deleting the end node of list if it's a duplicate one
                    if(dup) *pp = NULL;
                    return head;
                }
          };
    

    New to c++, I am just sharing for suggestions and tips for any improvement. Thx


Log in to reply
 

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