All submissions

Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

struct stack 
{
    int data[MAX];
    size_t size;
    size_t head;
};

void push(stack *s, int n)
{
    if (s->head == s->size)
        printf("Stack Overflow\n");
    else
    {
        s->data[s->head] = n;
        s->head++;
    }
}

void pop(stack *s)
{
    if (s->head == 0)
        printf("Stack Underflow\n");
    else
    {
        s->head--;
        printf("%d\n", s->data[s->head]);
    }
}

int main() {
    int n;
    scanf("%d", &n);

    char command[20];
    int number;
    stack stk = {.data = {0}, .size = MAX, .head = 0};
    for (int i = 0; i < n; i++)
    {
        scanf("%s %d", command, &number);
        if (command[1] == 'u')
            push(&stk, number);
        if (command[1] == 'o')
            pop(&stk);
    }

    return 0;
}

Solving Approach

 

 

 

Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow