Strange Bug with C++

  • 0

    Hi all,

    I'm working on a solution in C++, but having some difficulty. One of the issues I'm struggling with most is I don't know which node the problem wants returned, but I think returning a pointer to the head would be most logical. Regardless, a kick in the right direction would be greatly appreciated. Code below:

    class Solution {
        ListNode* removeElements(ListNode* head, int val) {
            ListNode* cur = head;
            ListNode* prev = NULL;
            // iterate
            while(cur != NULL) {
                // store prev
                prev = cur;
                // if val found
                if(cur->val == val) {
                    // remove node and reconfigure list
                    prev->next = cur->next;
                    cur->next = NULL;
                    delete cur; cur = NULL;
                // keep iterating
                cur = cur->next;
            return head;

    Thank you,

Log in to reply

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