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;   // use as TOP pointer: next free slot (top index)
    uint8_t tail;   // unused for stack, keep for compatibility
    uint8_t count;  // number of elements in stack
} stack;

void initialize(stack* s)
{
    s->head = 0;
    s->tail = 0;   // not used
    s->count = 0;
}

void push(stack* s, uint8_t data)
{
    if (s->count == MAX) {
        printf("Stack Overflow\n");
        return;
    }

    // head points to next free slot
    s->Buffer[s->head] = data;
    s->head++;
    s->count++;
}

int pop(stack* s, uint8_t* data)
{
    if (s->count == 0) {
        printf("Stack Underflow\n");
        return 0; // failure
    }

    // head is next free slot, so top element is at head-1
    s->head--;
    *data = s->Buffer[s->head];
    s->count--;
    return 1; // success
}

void process_stack(int n)
{
    stack s;
    initialize(&s);

    char line[64];

    for (int i = 0; i < n; i++) {
        if (fgets(line, sizeof(line), stdin) == NULL) {
            return;
        }

        // Remove trailing newline if present
        line[strcspn(line, "\r\n")] = '\0';

        if (strncmp(line, "push", 4) == 0) {
            int x;
            if (sscanf(line, "push %d", &x) == 1) {
                push(&s, (uint8_t)x);
            }
        } else if (strcmp(line, "pop") == 0) {
            uint8_t value;
            if (pop(&s, &value)) {
                printf("%u\n", value);
            }
        }
    }
}

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

    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