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 print_stack(int *stack){
    //Print stack
    printf("CURRENT STACK\n");
    for(int i=0;i<MAX;i++){
        printf("%d: %d\n",i,*(stack+i));
    }
}

void push_stack(int n, int *stack){ //Recieves number & stack array pointer
    //printf("N: %d, Stack[0]: %d\n",n,*stack);
    
    //OR
    //Step through stack & add value where the first 0/Null is
    for(int i=0;i<MAX;i++){
        if(*(stack+i)==NULL){
            //printf("%d is NULL\n",i);
            *(stack + i) = n; //Set the next available space of stack  = new number
            goto end;
        }
    }
    printf("Stack Overflow\n");
    end:
    //TEST
    //print_stack(stack);
   
}

void pop_stack(int* stack){
    for(int i=MAX-1;i>=0;i--){
        if(*(stack+i)!=NULL){
            printf("%d\n",*(stack+i)); //Print value at top of stack
            *(stack + i) = NULL; //Set the top of stack  = NULL (pop)
            goto end;
        }
    }
    printf("Stack Underflow\n");
    end:
    //print_stack(stack);
}

void process_stack(int n) {
    // Your logic here
    //1. Create a fixed sized array as stack
    int stack[MAX] = {NULL};

    //2. Scan input to get cmd and values    
    char cmd[10]; //Variable to hold string value from input
    int val; //Variable to hold val input

    for(int i=0;i<n;i++){
        scanf("%s", &cmd); //Get command
        //printf("Command: %s\n",cmd);
        
        if(strcmp(cmd,"push")==0){ //If command is push
            scanf("%d",&val); //Get push value
            push_stack(val,stack); //Push value to stack
        }
        else if(strcmp(cmd,"pop")==0){
            pop_stack(stack);
        }
    }


}



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

    process_stack(n);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote