Easy to understand c++ solution, no memleak


  • 0
    L
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode dummy(0);
            dummy.next = head;
            head = &dummy;
            while(head->next){
                if(head->next->val == val){
                    ListNode *temp = head->next;
                    head->next = temp->next;
                    delete temp;
                }else{
                    head = head->next;
                }
            }
            return dummy.next;
        }
    };

Log in to reply
 

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