Have you considered memory leak in C++?

  • 0

    Removing a node in the link list without actually delete the pointer may cause memory leak in C++.
    If the interviewer requires you to delete the dupilicates' pointers, how would you change your code?

    class Solution {
      ListNode *deleteDuplicates(ListNode *head) {
        if (!head) return 0;
        ListNode *ans = new ListNode(head->val-1);
        ListNode *tail = ans;
        int val=head->val-1;
        ListNode *p=head;
        while(p) {
            if (p->val==val || (p->next && p->next->val==p->val) ) {
                val = p->val;
                ListNode* q=p;
                delete q;
            else {
                val = p->val;
        if (tail) tail->next=0;
        ListNode *q=ans;
        ans = ans->next;
        delete q;
        return ans;

Log in to reply

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