All submissions

Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

int push(int stack[], int top, int val);
int pop(int stack[], int top);

int pop(int stack[], int top)
{
    if(top == -1)
    {
        printf("Stack Underflow\n");
        return top;
    }

    printf("%d\n", stack[top]);
    return --top;
}

int push(int stack[], int top, int val)
{
    if(top == MAX - 1)
    {
        printf("Stack Overflow\n");
        return top;
    }
    stack[++top] = val;
    return top;
}

void process_stack(int n) {
    int stack[MAX] = { 0 };
    int top = -1;
    char *tmp = (char *)malloc(20);
    int x = 0;
    int i;
    char *str;

    while(n)
    {
        x = 0;
        i = 0;
        str = (char *)malloc(20);
        scanf("%[^\n]%*c", str);
        while(str[i] != ' ' && str[i])
        {
            tmp[i] = str[i];
            i++;
        }
        tmp[i] = '\0';

        if(!strcmp(tmp, "pop"))
            top = pop(stack, top);
        else if(!strcmp(tmp, "push"))
        {
            i++;
            while(str[i])
            {
                int digit = str[i] - '0';  
                x = x * 10 + digit;
                i++;
            }
            top = push(stack, top, x);
        }
        n--;
        free(str);
        str = NULL;
    }
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow