88. Implement Stack Using Array with Push and Pop Operations

Back To All Submissions
Previous Submission
Next Submission

Code

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

#define MAX 10

void process_stack(int n) {
    int stack[MAX];
    char command[32];
    int8_t head = -1;

    for (int i = 0; i < n; ++i) {
        scanf("%s", command);
        // printf(">%s\r\n", command);

        switch (command[1]) {
            case 'o': // pop
                if (head == (-1)) {
                    printf("Stack Underflow\n");
                    break;
                }
                printf("%d\n", stack[head]);
                --head;
                break;
            case 'u': //push
                if (head >= (MAX - 1)) {
                    int dummy;
                    scanf("%d", &dummy);
                    printf("Stack Overflow\n");
                    break;
                }
                scanf("%d", &stack[++head]);
                break;
        }
    }

}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote