remove all nodes with same value in a linked list Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1-&gt;2-&gt;3-&gt;3-&gt;4-&gt;4-&gt;5, return 1-&gt;2-&gt;5.
Given 1-&gt;1-&gt;1-&gt;2-&gt;3, return 2-&gt;3.


The following is my code:

ListNode *getNextElement(ListNode *head, bool&amp; repeated){   
    while ((head-&gt;next) != NULL &amp;&amp;
            (head-&gt;val == head-&gt;next-&gt;val)){        
        head = head-&gt;next;
        repeated = true;            
    }

    return head-&gt;next;
}

ListNode *deleteDuplicates(ListNode *head) {
    ListNode *result = NULL;
    ListNode *copy_result = result;
    ListNode *next = NULL;

    for (ListNode *cur = head; cur != NULL; cur = next){
        bool cur_repeat = false;
        next = getNextElement(cur, cur_repeat);

        if (cur_repeat == true){
            while(cur!=next){
                ListNode *toFree = cur;
                cur = cur-&gt;next;
                delete toFree;
            }
        }
        else{
            if(result == NULL){
                result = cur;
                copy_result = result;
            }
            else{
                result-&gt;next = cur;
                result = result-&gt;next;
            }           
        }
    }

    if(result != NULL)
        result-&gt;next = NULL;
    return copy_result;
}
Iterate through the list and remember the pointer to the first element in the group node. Then check if the current element has the same value as the first element in the group. Remove the current element and set some flag to remember to remove the first element in this group. Then if you have a new value, set the first element pointer to this value and do it all over again.