Implement Stack Using Array with Push and Pop Operations

without using circular buffer

#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define MAX 10

void push(int* , uint8_t* ,const int);
void pop(int* , uint8_t* );

void process_stack(int n) {
    // Your logic here
    int stack[MAX], val = 0;
    uint8_t size = 0, i;
    char buffer[MAX];
    for(i  = 0; i<MAX; i++)     stack[i] = 0;
    for(i = n; i>0; i--){
        scanf("%s", buffer);
        if(strcmp(buffer, "push") == 0){
            scanf(" %d ", &val);
            push(stack, &size, val);
        }
        else{
            pop(stack, &size);
        }
    }
}
void push(int *stack, uint8_t *psize,const int val){
    if(*psize > MAX - 1){
        printf("Stack Overflow\n");
        return;
    }
    stack[*psize] = val;
    (*psize)++;     //*psize = *psize +1;
}
void pop(int *stack, uint8_t *psize){
    if(*psize <= 0){
        printf("Stack Underflow\n");
        return;
    }
    (*psize)--;
    printf("%d\n", stack[*psize]);
}

int main() {
    int n;
    scanf("%d", &n);
    getchar(); // Consume newline after number

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow