C++ Used dummy node and easy to understand. Illuminated with pictures.


  • 0
    A

    Keypoints: When the element is not removed, move both head and prehead pointer. When the element( '0' in the following pictures ) is removed, only move the head pointer.
    alt text
    alt text
    alt text

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

Log in to reply
 

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