26ms C++ solution (60.45% ahead others)

  • 0

    So far I've seen two kinds of solutions:

    1. Using recursion method.
    2. Using a fake head method.

    There is another solution that the iterative structure are similar to the fake head method.
    However, it doesn't make a fake head.
    Before the end that return the head.
    It checks if the head reserve the correspond value, if true, delete it.

    class Solution {
        ListNode* removeElements(ListNode* head, int val) {
            if( !head ) return head;
            // Using slow and fast pointers to avoid re-creations of pointer in each iteration.
            auto slow = head, fast = head->next;
                if(fast->val == val){
                    slow->next = fast->next;
                    delete fast;
                    fast = slow->next;
                } else {
                    slow = slow->next;
                    fast = fast->next;
            // Check head's value before return;
            if( head->val == val ){
                auto tmp = head;
                head = head->next;
                delete tmp;
            return head;

Log in to reply

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