Simple in-place C++ O(n)solution, beats 72.65%


  • 0
    M
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            
            if(head == NULL)
                return NULL;
            
            ListNode * currNode = head;
            ListNode * nextNode = head->next;
            
            while(nextNode != NULL)
            {
                if(currNode->val == nextNode->val)
                {
                    ListNode * temp = nextNode;
                    nextNode        = nextNode->next;
                    currNode->next  = nextNode;
                    free(temp);
                    
                }
                else
                {
                    nextNode = nextNode->next;
                    currNode = currNode->next;
                }
            }
            
            return head;
        }
    };

  • 0
    C

    It seems these syntax :ListNode *temp = nextNode; free(temp) are not used.


  • 0
    Y

    please submit again, it cannot beats 72.65% any more.


Log in to reply
 

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