Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10
typedef struct {
    uint8_t buffer[MAX];
    uint8_t head;
    uint8_t count;
} My_stack_t; 

// ---------------------------------------
void stack_push(My_stack_t *stck, uint8_t data)
{
    if(stck->count == MAX)
    {   
        printf("Stack Overflow\n");
        return;
    }
    
    stck->buffer[stck->head] = data;
    stck->head = (stck->head + 1);
    stck->count = stck->count + 1;
}

// ---------------------------------------
void stack_pop(My_stack_t *stck)
{
    if(stck->count == 0)
    {
        printf("Stack Underflow\n");
        return; 
    }
    stck->head = stck->head - 1; 
    printf("%d\n", stck->buffer[stck->head]);
    stck->count = stck->count - 1; 
}

// ---------------------------------------
void process_stack(int n) {
    // Your logic here
    My_stack_t mstack = { .buffer = { 0 }, .head = 0, .count = 0 };
    char cmd[4];
    int value; 
    while(n > 0)
    {   scanf("%s %d", cmd, &value);
        if(strcmp(cmd, "pop") == 0)
        {
            stack_pop(&mstack);
            
        }
        else
        {
            stack_push(&mstack, value);
            
        }
        n--;         
    }
}

// ---------------------------------------
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