Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10
#define NAME_LEN 10

typedef struct 
{
    uint8_t buffers[MAX];
    uint8_t top;
    uint8_t count;   
}stack;

char name[NAME_LEN];
int value=0;   

void read_command(void)
{
    scanf("%9s", name);   
    if (strcmp(name, "push") == 0)
    {
        scanf("%d", &value);
       // printf("%d", value);
    }
}

void process_stack(stack *s, int n) {
    // Your logic here
    int poped;

     if (strcmp(name, "push") == 0)
    {
        
        if(s->count == MAX)
        printf("Stack Overflow\n");
        else
        {
            s->buffers[s->top] = value;
           // printf("%d\n", s->buffers[s->top]);
            s->top = s->top+1;
            s->count++;         
        }
    }
    else if (strcmp(name, "pop") == 0)
    {
        
        if(s->count == 0)
        printf("Stack Underflow\n");
        else
        {
            poped = s->buffers[s->top-1];
            s->top--;
            s->count--;  
            printf("%u\n", poped);       
        }
        
    }

  
   
}

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

    for( int i=0; i<n; i++)
    {
       read_command(); // Consume newline after number
       process_stack(&s, n);
         //if(i<n-1)
          //printf(" ");
    }
       
       
   
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow