aboutsummaryrefslogtreecommitdiff
path: root/Computer_Science/data_structures/chapter_3/stack_array.c
blob: 57a7fadb4a9078b3b143f0f1895df2595da7d669 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <stdlib.h>

#include "stack_array.h"

#define EMPTY_TOS (-1)
#define MIN_STACK_SIZE (5)

struct stack_record
{
    int capacity;
    int top_of_stack;
    elem *array;
};

stack create_stack(int max_elements)
{
    stack s;

    if(max_elements < MIN_STACK_SIZE)
        printf("size too small.\n");

    s = malloc(sizeof(struct stack_record));
    if(s == NULL)
        printf("out of space");

    s->array = malloc(sizeof(elem) * max_elements);

    if(s->array == NULL)
        printf("out of space");

    s->capacity = max_elements;
    make_empty(s);

    return s;
}

void dispose_stack(stack s)
{
    if(s != NULL) {
        free(s->array);
        free(s);
    }
}

int is_empty(stack s)
{
    return s->top_of_stack == EMPTY_TOS;
}

void make_empty(stack s)
{
    s->top_of_stack = EMPTY_TOS;
}

void push(elem x, stack s)
{
    if(s->top_of_stack >= s->capacity)
        printf("full stack");
    else
        s->array[++s->top_of_stack] = x;

}

elem top(stack s)
{
    if(!is_empty(s))
        return s->array[s->top_of_stack];

    printf("empty stack");
    return 0;
}

void pop(stack s)
{
    if(!is_empty(s))
        s->top_of_stack--;

    printf("empty stack");
}

elem top_and_pop(stack s)
{
    if(!is_empty(s))
        /* take care of this, before return, s->top_of_stack is already dec. */
        return s->array[s->top_of_stack--];

    printf("empty stack");
    return 0;
}

int main()
{
    stack s = create_stack(100);
    push(1, s);
    push(2, s);
    push(3, s);
    printf("%d\n", top_and_pop(s));
    printf("%d\n", top_and_pop(s));
    return 0;
}