lundi 25 décembre 2017

Using deleted variable - is it depending on compiler?

The following codes are to remove duplicates from a sorted list. It runs OK on my computer. My question is about using

head = head->next;

after

delete head;

below. Is it illegal? The codes generate correct results on my compiler. Will it depend on compiler? Or it complies with C++11 standards?

struct ListNode {
    int val;
    ListNode *next;
    explicit ListNode(int x) : val(x), next(nullptr) { }
};


class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head && (head->next = deleteDuplicates(head->next)) && head->next->val == head->val){
            delete head;
            head = head->next;
        }
        return head;
    }
};


int main() {
    ListNode *h = new ListNode(0);
    auto cur=h;
    cur->next= new ListNode(1);
    cur=cur->next;
    cur->next= new ListNode(2);
    cur=cur->next;
    cur->next= new ListNode(2);
    cur=cur->next;

    Solution sol;
    auto xx=sol.deleteDuplicates(h);
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire