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

void pop_stack(int arr[], int& head)
{
    if(head == -1)
    {
        printf("Stack Underflow\n");
       // return;
    }
    else{
        printf("%d\n" , arr[head]);
        head--;
       // return;
    }
    return;
}

 void push_stack(int arr[] , int& head , int val)
 {
    if(head >= (MAX - 1))
    {
        printf("Stack Overflow\n");
    }
    else
    {
        head++;
        arr[head] = val;
    }
    return;
 }

void process_stack(int n) {
    // Your logic here
    int arr[MAX];

    int arr_ptr = -1;
    char cmd[10];
    char buffer[100];
    int val;
    for(int i=0; i < n; i++)
    {
       //scanf("%s", &cmd);
       fgets(buffer ,sizeof(buffer) , stdin);
       sscanf(buffer , "%s %d" , cmd, &val);
       if(strcmp(cmd,"push") == 0)
       {
        // printf("val = %d" , val);
         //call push stack
         push_stack(arr , arr_ptr , val);
       }
       else if(strcmp(cmd , "pop") == 0)
       {
        // call pop stack
          pop_stack(arr,arr_ptr);
       }
       else{ printf("invalid cmd"); return;}

    } 
}

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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote