Elements are not removed from the stack

Viewed 30

The deleteEven() method doesn't work, the program goes to infinite output, help fix it

Stack:

typedef struct Node{
    int value;
    struct Node *next;
} NODE, *pNODE;

typedef struct Stack{
    pNODE top;
    int len;
} STACK, *pSTACK;

Method:

void deleteEven(pSTACK pS){
    pNODE pN = pS->top;

    while(pN){
        if(pN->value % 2 == 0){
            pNODE del = pN;
            pN = pN->next;
            free(del);  
        }   
        else
            pN = pN->next;
    }
}
1 Answers

Within the function the pointer top is not changed when the pointed node contains an even value. And the data member next of the previous node before the deleted node also is not changed.

The function can be defined the following way.

void deleteEven( pSTACK pS )
{
    pNODE *pN = &pS->top;

    while( *pN != NULL )
    {
        if( ( *pN )->value % 2 == 0 )
        {
            pNODE del = *pN;
            *pN = ( *pN )->next;
            free( del );  
        }   
        else
        {
            pN = & ( *pN )->next;
        }
    }
}

Do not forgot initially to set the data member top to NULL when the stack is declared.

Related