-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathstack.c
81 lines (68 loc) · 1.21 KB
/
stack.c
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
#include <stdlib.h>
#include "stack.h"
struct stack_t *
create_stack (int capacity)
{
struct stack_t * stack = (struct stack_t *) malloc(sizeof(struct stack_t)) ;
stack->capacity = capacity ;
stack->size = 0 ;
stack->buffer = (int *) calloc(capacity, sizeof(int)) ;
return stack ;
}
void
delete_stack (struct stack_t * stack)
{
free(stack->buffer) ;
free(stack) ;
}
int
push (struct stack_t * stack, int elem)
{
if (is_full(stack))
return 0 ;
stack->buffer[stack->size] = elem ;
stack->size += 1 ;
return 1 ;
}
int
pop (struct stack_t * stack, int * elem)
{
if (is_empty(stack))
return 0 ;
*elem = stack->buffer[stack->size - 1] ;
stack->size -= 1 ;
return 1;
}
int
top (struct stack_t * stack, int * elem)
{
if (is_empty(stack))
return 0 ;
*elem = stack->buffer[stack->size - 1] ;
return 1;
}
int
is_empty (struct stack_t * stack)
{
return (stack->size == 0) ;
}
int
is_full (struct stack_t * stack)
{
return (stack->size == stack->capacity) ;
}
int
get_size (struct stack_t * stack)
{
return stack->size ;
}
int
get_elem (struct stack_t * stack, int index, int * elem)
{
if (index < 0)
return 0 ;
if (stack->size <= index)
return 0 ;
*elem = stack->buffer[index] ;
return 1 ;
}