One-Liner in Ruby

  • 11

    Recursively remove duplicates from the rest of the list, then possibly drop the head (if it's a duplicate of the value after it).


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

    Bad C++ versions:

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

    As @shawnyi pointed out, that leaks memory. So delete:

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

    As @drbombe pointed out, I shouldn't access h->next after deleting h. Not sure what I was thinking. I certainly knew that. I guess I just focused on the algorithm and didn't care as long as it gets accepted (which it does).

    For a proper version, see @drbombe's solution below.

  • 0


  • 2

    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.

  • 1

    @StefanPochmann You use h = h->next after delete h. Is it an undefined behavior?

  • 0

    @drbombe Uh, yeah, that doesn't look right. No idea what I was thinking. I'll add a note, thanks.

  • 1

    @StefanPochmann How about these codes based on your idea.

    class Solution {
    	ListNode* deleteDuplicates(ListNode* head) {
    		if (head && (head->next = deleteDuplicates(head->next)) && head->next->val == head->val){
    			auto oldhead=head;
    			head = head->next;
    			delete oldhead;
    		return head;

  • 0

    @drbombe Yes, that looks good. Or at least correct. I just really wanted it to be a one-liner :-)

    I now took the focus off of C++ and put it on the Ruby version instead. That's much better anyway. I think I wrote my C++ solution first and just focused on the algorithm, that's how this happened.

Log in to reply

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