-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.c
More file actions
62 lines (56 loc) · 1.08 KB
/
stack.c
File metadata and controls
62 lines (56 loc) · 1.08 KB
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
#include "stack.h"
#include <stdlib.h>
stack_t *stack_create()
{
stack_t *stack = (stack_t *)malloc(sizeof(stack_t));
stack->top = NULL;
stack->count = 0;
return stack;
}
void stack_destroy(stack_t *stack)
{
while (stack->top != NULL)
{
pop(stack);
}
free(stack);
}
// Push on the stack
void push(stack_t *stack, point_t point)
{
if (stack->top == NULL)
{
stack->top = (snode_t *)malloc(sizeof(snode_t));
stack->top->p = point;
stack->top->next = NULL;
}
else
{
snode_t *node = (snode_t *)malloc(sizeof(snode_t));
node->p = point;
node->next = stack->top;
stack->top = node;
}
stack->count++;
}
point_t pop(stack_t *stack)
{
if (stack->top == NULL)
{
return (point_t){-1, -1};
}
point_t p = stack->top->p;
snode_t *node = stack->top;
stack->top = stack->top->next;
stack->count--;
free(node);
return p;
}
point_t top(stack_t *stack)
{
if (stack->top == NULL)
{
return (point_t){-1, -1};
}
return stack->top->p;
}