All submissions

Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10

typedef struct {
    int arr[MAX];
    int tail;
    int head=0;
    int new_data;
    int count=0;

} buffer;
void process_stack(int n) {
  char str[4];
  buffer b1;

  for(int i=0;i<n;i++)
  {
     
    scanf("%s",str);
    if(strcmp(str,"push")==0)
    {
        if(b1.count<MAX)
        {
        scanf("%d\n",&b1.new_data);
        b1.arr[b1.count]=b1.new_data;//0:10 ///1:20
        b1.count+=1;
        }
        else
        {
            printf("Stack Overflow\n");
        }
    }
    else
    {
        if(b1.count>=1)
        {
              b1.count-=1;
             
            printf("%d\n", b1.arr[b1.count]);
          
        }
         else
         {
                printf("Stack Underflow\n");
         }
        
    }

    b1.head+=1;
  }
}

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