-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdouble_stack.c
More file actions
64 lines (53 loc) · 1.44 KB
/
double_stack.c
File metadata and controls
64 lines (53 loc) · 1.44 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
63
64
#include <stdlib.h>
#include <math.h>
#include "global.h"
#include "double_stack.h"
void init_double_stack_s(struct double_stack_s *stack)
{
stack->nalloc = stack->n = 0;
stack->values = NULL;
}
void free_double_stack_s(struct double_stack_s *stack)
{
if (stack->values)
free(stack->values);
init_double_stack_s(stack);
}
void push_double(struct double_stack_s *stack, double value)
{
if (stack->n == stack->nalloc) {
stack->nalloc += REALLOC_INCREMENT;
stack->values =
realloc(stack->values, sizeof *stack->values * stack->nalloc);
}
stack->values[stack->n++] = value;
}
double pop_double(struct double_stack_s *stack)
{
double value = NAN;
if (stack->n > 0) {
value = stack->values[--stack->n];
if (stack->n == 0)
free_double_stack_s(stack);
else if (stack->n == stack->nalloc - REALLOC_INCREMENT) {
stack->nalloc -= REALLOC_INCREMENT;
stack->values =
realloc(stack->values, sizeof *stack->values * stack->nalloc);
}
}
return value;
}
int find_double(struct double_stack_s *stack, double value)
{
int i;
for (i = 0; i < stack->n; i++)
if (stack->values[i] == value)
return i;
return -1;
}
int compare_doubles(const void *p1, const void *p2)
{
double value1 = *((double *)p1);
double value2 = *((double *)p2);
return (value1 > value2) - (value1 < value2);
}