Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove elements from link list whose sum equals to zero

Tags:

algorithm

Given a list in form of linked list, I have to canceled out all the resources whose sum up to 0(Zero) and return the remaining list.

Like

6 -6 3 2 -5 4 returns 4
8 10 4 -1 -3 return 8 10

I only need algorithm to solve this question.

like image 359
saurabh Avatar asked Jul 24 '16 19:07

saurabh


2 Answers

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

see on wiki or google it to see articles about that

like image 195
M.Khooryani Avatar answered Oct 09 '22 14:10

M.Khooryani


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;
    }
}
like image 41
Santoshkumar Avatar answered Oct 09 '22 16:10

Santoshkumar