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;
} stack1;
stack1 stack;

void process_stack(int n) {
    // Your logic here
    for (int i = 0; i < n; i++) {
    char cmd[10];
    scanf("%s", cmd);

    if (strcmp(cmd, "push") == 0) {
        int x;
        scanf("%d", &x);
        // xử lý push x
        if (stack.head == MAX) printf("Stack Overflow\n");
        else {
            stack.buffer[stack.head] = x;
            stack.head++;
            stack.count++;
        }
    } else if (strcmp(cmd, "pop") == 0) {
        // xử lý pop
        if (stack.count == 0) {
            printf("Stack Underflow\n");
        } else {
            printf("%d\n",stack.buffer[stack.head-1]);
            stack.head--;
            stack.count--;
        }
    }
}
}

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