-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.h
66 lines (57 loc) · 1.22 KB
/
stack.h
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
#include <string.h>
typedef struct Block {
Horizont elements[STACK_BLOCK];
int top;
struct Block *prev;
struct Block *next;
} Block;
Block *stack_block_alloc(Block *prev)
{
Block *new = malloc(sizeof(Block));
new->top = 0;
new->next = NULL;
new->prev = prev;
if(prev != NULL)
prev->next = new;
return new;
}
Block *stack_push(Block *stack, Horizont *el)
{
if(stack->top == STACK_BLOCK)
{
if(stack->next != NULL){
stack = stack->next;
}
else
stack = stack_block_alloc(stack);
}
memcpy(&stack->elements[stack->top], el, sizeof(Horizont));
stack->top++;
return stack;
}
Horizont *stack_peek(Block *stack)
{
if(stack->top == 0)
return NULL;
return &stack->elements[stack->top-1];
}
Block *stack_pop(Block *stack, Horizont *el)
{
if(stack->top == 0)
return NULL;
stack->top--;
memcpy(el, &stack->elements[stack->top], sizeof(Horizont));
if(stack->top == 0 && stack->prev!=NULL)
return stack->prev;
return stack;
}
void stack_free(Block* start)
{
Block *next;
while(start != NULL)
{
next = start->next;
free(start);
start = next;
}
}