Skip to content
Snippets Groups Projects
Select Git revision
  • da2c2fb550409c85fc471e56e155acb51f5703d9
  • main default protected
  • 3-add-makefile-with-structure
  • 9-add-destroy-function-4
  • 4-add-create-init-function
  • 5-add-push-function-2
  • 9-add-destroy-function-3
  • 9-add-destroy-function-2
  • v0.1
9 results

stack.c

Blame
  • richarda.tyarks's avatar
    richarda.tyarks authored
    # Conflicts:
    #   README.md
    #   stack.c
    da2c2fb5
    History
    stack.c 1.71 KiB
    #include <stdio.h>
    #include <stdlib.h>
    
    #define DEFAULT_CAPACITY 4
    
    void stack_init(stack *s) {
        s->top      = -1;
        s->capacity = DEFAULT_CAPACITY;
        s->data     = malloc(sizeof(int) * DEFAULT_CAPACITY);
    }
    
    void stack_destroy(stack *s) {
        free(s->data);
        s->data     = NULL;
        s->capacity = -1;
        s->top      = -1;
    }
    
    void stack_push(stack *s, int value)
    {
        if (s->top == s->capacity-1)
        {
            assert(s->data = realloc(s->capacity * 2 * sizeof(int)) && "Error : realloc failed");
        }
        
        s->top++;
        s->data[s->top] = val;
    }
    
    void stack_pop(stack *s, int *value) {
        if (stack_is_empty(*s)) {
            return;
        }
        if (s->top == s->capacity / 4) {
            s->capacity /= 2;
            s->data = realloc(s->data, sizeof(int) * s->capacity);
        }
    
        *value = s->data[s->top];
        s->top -= 1;
    }
    
    void stack_peek(stack s, int *value) {
        if (!stack_is_empty(s)) {
            *value = s.data[s.top];
        }
    }
    
    void stack_print(const stack s) {
        // TODO: replace if statement with following as soon as relevant function is
        // implemented if (!stack_is_empty()) {
        if (s.top >= 0) {
            printf("          TOP\n--------------------\n");
            for (int *spot = s.data + s.top; spot >= s.data; --spot) {
                printf("%8ld |  %12d\n", spot - s.data, *spot);
            }
            printf("--------------------\n          BOTTOM\n");
        } else {
            printf("STACK EMPTY\n");
        }
    }
    
    void stack_clone(stack s, stack *clone) {
        clone->top      = s.top;
        clone->capacity = s.capacity;
        clone->data     = malloc(sizeof(int) * s.capacity);
        for (int i = 0; i <= s.top && i < s.capacity; i++) {
            clone->data[i] = s.data[i];
        }
    }
    
    int get_length(stack s) {
        return s.top + 1;
    }