Clear and concise solution. Using 4 pointers.


  • 0

    I think this problem is really hard, because have to deal with a lot of conditions at the same time.

    class Solution {
    public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* res=nullptr;
        ListNode* tail=nullptr;
        ListNode* l=head;
        ListNode* r=head?head->next:nullptr;
        while(l){
            if(r==nullptr||l->val!=r->val){
                if(l->next==r){ // with different vals, only here we know l could be added.
                    res=res?res:l;
                    if(tail) tail->next=l;
                    tail=l;
                    tail->next=nullptr;
                }
                l=r;
            }
            r=r?r->next:nullptr;
        }
        return res;
    }};

Log in to reply
 

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