One-Liner in C++ / Ruby

  • 11
    return h && (h->next = deleteDuplicates(h->next)) && h->next->val == h->val ? h->next : h;

    Update after shawnyi's comment:

    While the above does remove the duplicates from the list, it doesn't delete the nodes from memory, causing memory leaks. Here's a version which takes care of that.

    if (h && (h->next = deleteDuplicates(h->next)) && h->next->val == h->val) delete h, h = h->next; return h;

    I wouldn't really write it like that, though, so it doesn't really deserve the label "one-liner". I guess I should've just written it in let's say Ruby in the first place, which has garbage collection. It's even shorter there anyway, since it doesn't use arrows and doesn't need the return keyword.

    def delete_duplicates(h)
        h && ( = delete_duplicates( && == h.val ? : h

  • 0


  • 1

    have you deleted the relative node? It seems there exists memory leakage, am I right? = =!

  • 0

    @shawnyi Yes, you're right, I was sloppy there. I just wanted to show the technique, but I shouldn't have ignored the memory leaks. I updated it now. Thanks.

Log in to reply

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