-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.c
71 lines (58 loc) · 1.35 KB
/
set.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "set.h"
void set_init(struct set * st)
{
st->first = NULL;
}
struct node * set_first(struct set * st)
{
return st->first;
}
void set_add(struct set * st, const char * data)
{
if (st->first == NULL)
{
// create and store first element
st->first = malloc(sizeof(struct node));
st->first->data = strdup(data);
st->first->next = NULL;
}
else
{
// iterate over set to check for duplicates
struct node * ptr = st->first;
if (strcmp(ptr->data, data) == 0)
return;
while (ptr->next != NULL)
{
ptr = ptr->next;
if (strcmp(ptr->data, data) == 0)
return;
}
// if not returned, create and store the new element
ptr->next = malloc(sizeof(struct node));
ptr->next->data = strdup(data);
ptr->next->next = NULL;
}
}
const char * set_data(struct node * node)
{
return node->data;
}
struct node * set_next(struct node * node)
{
return node->next;
}
void set_free(struct set * st)
{
// iterate over the whole list and free all of the structures
while (st->first != NULL)
{
struct node * next = st->first->next;
free(st->first->data);
free(st->first);
st->first = next;
}
}