Repository navigation
Expand file tree
/
Copy pathDFS.c
More file actions
106 lines (90 loc) · 2.03 KB
/
Copy pathDFS.c
File metadata and controls
106 lines (90 loc) · 2.03 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "DFS.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/* private functioons */
static int gstack_resize(gstack * s);
/*
* 0 <= top <= capacity
* stack[0 ... top-1] = valid elements
* stack[top ... capacity-1] = free space
*/
gstack * gstack_init(void){
gstack *s = malloc(sizeof(gstack));
if (!s){
perror("malloc");
return NULL;
}
vertex ** stack = malloc(sizeof(vertex *) * MIN_STACK_SIZE);
if (!stack){
perror("malloc");
free(s);
return NULL;
}
s->stack = stack;
s->top = 0;
s->capacity = MIN_STACK_SIZE;
return s;
}
/*
* Capacity always starts at MIN_STACK_SIZE and changes only
* by powers of two (x2 on grow, /2 on shrink).
* Therefore, if capacity > MIN_STACK_SIZE, then capacity / 2
* is guaranteed to be >= MIN_STACK_SIZE.
*/
static int gstack_resize(gstack * s){
if (!s)
return -1;
int new_capacity;
if (s->top == s->capacity)
new_capacity = s->capacity * 2;
else if ( s->capacity >= 4 * s->top && s->capacity > MIN_STACK_SIZE)
new_capacity = s->capacity /2;
else
return 0;
vertex ** new_stack = malloc(sizeof(vertex *) * new_capacity);
if (!new_stack){
perror("malloc");
return -2;
}
memcpy(new_stack, s->stack, (size_t)s->top * sizeof(vertex*));
free(s->stack);
s->stack = new_stack;
s->capacity = new_capacity;
return 0;
}
int g_push (gstack *s, vertex * node){
if (!s)
return -1;
if (!node)
return -3;
if (s->top == s->capacity){
int err = gstack_resize(s);
if (err != 0)
return err;
}
s->stack[s->top] = node;
s->top ++;
return 0;
}
vertex * g_pop (gstack *s){
if (!s)
return NULL;
if (s->top == 0)
return NULL;
s->top --;
vertex * node = s->stack[s->top];
if (s->capacity >= 4 * s->top && s->capacity > MIN_STACK_SIZE){
int err = gstack_resize(s);
if(err != 0)
fprintf(stderr, "Warning: resize failed with code: %d, pop succeded", err);
}
return node;
}
int gstack_drop (gstack *s){
if (!s)
return -1;
free(s->stack);
free(s);
return 0;
}