Implement Stack Using Array with Push and Pop Operations

Code

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

#define MAX 10 
#define POP_UNDERFLOW -2000

typedef struct{
    int buffer[MAX];
    int stack_pointer; 
    int capacity;
    int count;
}Stack_t; 

void create_stack(Stack_t *st){
    st->count = 0; 
    st->capacity = MAX; 
    st->stack_pointer = -1; 
}

bool isFull(Stack_t *st){
    return st->count == st->capacity; 
}

bool isEmpty(Stack_t *st){
    return st->count == 0; 
}

void push_stack(Stack_t *st, int item){
    if(isFull(st)){
        printf("Stack Overflow\n");
        return;
    }
        st->stack_pointer++; 
        st->buffer[st->stack_pointer] = item; 
        st->count++;
}

int pop_stack(Stack_t *st){
    if(isEmpty(st)){
        printf("Stack Underflow\n");
        return POP_UNDERFLOW; 
    }
    int item;
    if(st->count > 0){
        item = st->buffer[st->stack_pointer];
        st->stack_pointer--; 
        st->count--;
    }
    return item;
}

void handle_stack(Stack_t *st, int n){
    char line[64]; 
    int item;

    int c = getchar();
    if(c != '\n' && c != EOF){
        ungetc(c,stdin); 
    }

    for(int i = 0; i<n; i++){
        fgets(line, sizeof(line), stdin);
        line[strcspn(line,"\n")] = '\0';



        if(strncmp(line, "push", 4) == 0){
            if(sscanf(line, "push %d",&item) == 1){
                push_stack(st,item);
            }
            else{
                printf("Sai so lieu\n");
            }
        }
        else if(strcmp(line, "pop") == 0){
            int item = pop_stack(st); 
            if(item != POP_UNDERFLOW){
                printf("%d\n",item);
            }
        }
        else{
            printf("Loi cu phap\n");
        }
    }
}

int main(){
    Stack_t st;
    create_stack(&st);
    int n;
    scanf("%d",&n);
    handle_stack(&st, n);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 push 10 push 20 pop pop pop

Expected Output

20 10 Stack Underflow