blob: 846d933503bde2e42e7779239b38a125652ffb28 (
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
|
#include "position_stack.h"
#include <stdio.h>
#include <stdlib.h>
// Error handler for stack errors
void stack_error(int err)
{
switch (err)
{
case STACK_ERR_OVERFLOW:
printf("Error: Stack overflow\nBe kind and report this problem.");
break;
case STACK_ERR_UNDERFLOW:
printf("Error: Stack underflow\nBe kind and report this problem.");
break;
}
exit(1);
}
// Creates a new stack
PositionStack *pos_stack_create(int capacity)
{
PositionStack *pos_stack = malloc(sizeof(PositionStack));
pos_stack->capacity = capacity;
pos_stack->top = -1;
pos_stack->items = malloc(sizeof(Position) * capacity);
return pos_stack;
}
void pos_stack_destroy(PositionStack *pos_stack)
{
free(pos_stack->items);
free(pos_stack);
}
// Adds a new item to a stack
void pos_stack_push(PositionStack *pos_stack, Position pos)
{
// Avoid a overflow by checking if the stack is full
if (pos_stack->top == pos_stack->capacity - 1)
{
stack_error(STACK_ERR_OVERFLOW);
}
// Add an element and increase the top index
pos_stack->items[++pos_stack->top] = pos;
}
// Returns the topmost item of a stack
Position pos_stack_peek(PositionStack *pos_stack)
{
// Avoid a underflow by checking if the stack is empty
if (pos_stack->top == -1)
{
stack_error(STACK_ERR_UNDERFLOW);
}
return pos_stack->items[pos_stack->top];
}
// Deletes the topmost item of a stack
Position pos_stack_pop(PositionStack *pos_stack)
{
// Avoid a underflow by checking if the stack is empty
if (pos_stack->top == -1)
{
stack_error(STACK_ERR_UNDERFLOW);
}
// Decrease the stack size by 1 and return the popped element
return pos_stack->items[pos_stack->top--];
}
|