The answer you are wished to offer when in an interview!!

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

  • 0

    Is it not necessary to free the nodes that we're removing from the list? What about memory leak?

  • 0

    remarkable indeed. but what if the ListNode's val member is not as trivial as an int?

Log in to reply

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