remove elements from link list whose sum equals to zero

this is actually the classic subset sum problem which is NP-complete

see on wiki or google it to see articles about that


The following function just prints the nodes except the ones which are canceled out, you can make it push to a new list and return.

void printExCancel( node* head )
{
    node* start = head;
    node* end;

    while ( start )
    {
        bool mod = false;
        int sum = 0;
        end = start;
        while ( end )
        {
            sum += end->data;
            if ( sum == 0 )
            {
                start = end;
                mod = true;
                break;
            }
            end = end->next;
        }
        if ( mod == false ) {
            //push to new list
            printf( "%d\n", start->data );
        }
        //else {
        //    call funtion to delete from start to end
        //}
        start = start->next;
    }
}

Tags:

Algorithm