Share my C++ solution with 2 pointers


  • -1
    Y
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode *last=head;
            ListNode *result=head;
            while (head) {
                if (head->val==val) {
                    if (last!=head) {
                        head=head->next;
                        last->next=head;
                    }
                    else{
                        result=last=head=head->next;
                    }
                }
                else{
                    if (last!=head) {
                        last=last->next;
                    }
                    head=head->next;
                }
            }
            return result;
        }
    };

  • 0
    Q

    I think" result = last =head =head->next " can be replaced by " last = head =head ->next"


  • 0
    Y

    I use the result val to keep the head of the list after removing elements.


Log in to reply
 

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