7-line C++ Iterative Solution


  • 2

    I saw many people are discussing whether to delete the removed nodes. I think if you want to delete something, you must make sure it is dynamically allocated on the heap. As the question didn't tell us, we don't need to delete them. Correct me if I'm wrong.

    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) 
        {
            ListNode* curr=head;
            while(curr) 
                if(curr->next)
                    curr->val==curr->next->val?curr->next=curr->next->next:curr=curr->next;
                else    
                    break;
            return head;
        }
    };
    

    Besides, I also wondering how to make it more concise, like

    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) 
        {
            ListNode* curr=head;
            while(curr) 
                curr->next?(curr->val==curr->next->val?curr->next=curr->next->next:curr=curr->next):break;
            return head;
        }
    };
    

    But I'm getting syntax error. How to do this correctly?


  • 1
    J

    I don't think you delete the duplicates ,and it leads to a memory leak.


Log in to reply
 

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