Search code examples
arrayscstack

Minium value of a stack in C


i'm trying to implement a funcion who calculate the minium value of a stack in C implemented with an array, using only push() and pop() function. here is my code: (findMin() is the last function).

The function doesn't work, if i put 5 3 5 5 5 in the stack, it prints "minium value 1". I think it's because i can't find a correct base condition

void init(int S[]){
    S[0] = 0;
}

int push(int S[], int x) {
    
    if(!fullStack(S)){
        S[0] = S[0] + 1;
        S[S[0]] = x;
    }
    else printf("stack full\n");

}

int pop(int S[]) {
    if(!emptyStack(S)){
        int x = S[S[0]];
        S[0]--;
        return x;
    }
    else {
        printf("stack empty\n");
        return -1;
    }
}

int emptyStack(int S[]) {
    return S[0] == 0;
}


int fullStack(int S[]) {
    return S[0] == SIZE;
}
int findMin(int S[]){
    if(emptyStack(S)) return ;
    else{
        int x = pop(S);
        if(x < findMin(S)) return x;
        else return findMin(S); 
        push(S, x);
    }
    
}

Solution

  • Interesting logic...

    By what i could understand, here is what you need to do,

    #define LARGE_NUMBER 1000; //You could look into INT_MAX
    
    int findMin(int S[]){
        if(emptyStack(S)) return LARGE_NUMBER; 
        else{
            int x = pop(S);
            int y = findMin(S); // Store result in separate variable to return
            if(x < y) return x;
            else return y; 
            push(S, x); // This is unreachable code, so stack becomes empty
        }
        
    }
    

    After these changes, findMin() returns "3" in your case when input is "5 3 5 5 5".