My easy c++ solution


  • 6
    Y
    ListNode* removeElements(ListNode* head, int val) {
        ListNode** tmp = &head;
        while(*tmp){
            if((*tmp)->val == val) *tmp = (*tmp)->next;
            else tmp = &((*tmp)->next);
        }
        return head;
    }

  • 0
    N

    you should clean up the memory by deleting the node.


  • 0
    G

    So cool, although you forgot to clean up the memory.


  • 0
    T

    Can you show the code to clean up the memory in this case.

    Thanks I am new.


  • 0
    Y

    ListNode* removeElements(ListNode* head, int val) {
    ListNode** tmp = &head;
    ListNode* del = NULL;
    while(*tmp){
    if((*tmp)->val == val) {
    del = *tmp;
    *tmp = (*tmp)->next;
    delete del;
    del = NULL;
    }
    else tmp = &((*tmp)->next);
    }
    return head;
    }


Log in to reply
 

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