How to implement stack of characters in C

1 Answer

0 votes
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char* data;
    int top;
    int capacity;
} Stack;

void initialize(Stack* stack) {
    stack->data = malloc(sizeof(char) * 10);
    stack->top = -1;
    stack->capacity = 10;
}

void push(Stack* stack, char ch) {
    if (stack->top == stack->capacity - 1) {
        stack->capacity *= 2;
        stack->data = realloc(stack->data, sizeof(char) * stack->capacity);
    }
    
    stack->data[++stack->top] = ch;
}

char pop(Stack* stack) {
    if (stack->top == -1) {
        return '\0';
    }
    
    return stack->data[stack->top--];
}

bool print(Stack stack) {
    for (int i = 0; i < stack.top + 1; i++) {
        printf("%c ", stack.data[i]);
    }
    printf("\n");
}

bool free_stack(Stack stack) {
    free(stack.data);
}

int main() {
    Stack stack;
    
    initialize(&stack);
    
    push(&stack, 'c');
    push(&stack, 'p');
    push(&stack, 'r');
    push(&stack, 'o');
    push(&stack, '!');

    print(stack);
    
    pop(&stack);
    pop(&stack);

    print(stack);
    
    free_stack(stack);

    return 0;
}

  
  
  
/*
run:
  
c p r o ! 
c p r 
  
*/

 



answered Mar 9, 2024 by avibootz
edited Mar 9, 2024 by avibootz
...