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

int arr[MAX];

int currIdx;

void push(int n)
{
    arr[++currIdx] = n;
}

int pop()
{
    int ret = arr[currIdx];
    currIdx--;
    return ret;
}

void process_stack(int n) {
    while(n--)
    {
        char cmd[10];
        scanf("%9s", cmd);
        if(strcmp(cmd, "push") == 0)
        {
            int val;
            scanf("%d",&val);
            if(currIdx == 9) printf("Stack Overflow\n");
            else push(val);
        }
        else
        {
            if(currIdx == -1) printf("Stack Underflow\n");
            else printf("%d\n",pop());
        }
    }
}

int main() {
    int n;
    memset(arr,0,sizeof(arr));
    currIdx = -1;
    scanf("%d", &n);
    getchar(); // Consume newline after number

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote