Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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

Related questions

1 answer 193 views
1 answer 191 views
191 views asked Mar 31, 2018 by avibootz
1 answer 222 views
1 answer 55 views
...