-
Notifications
You must be signed in to change notification settings - Fork 0
/
sll.c
99 lines (84 loc) · 1.93 KB
/
sll.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* SPDX-License-Identifier: GPL-2.0+
* Copyright (C) 2018 Abinav Puthan Purayil
* */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
#include "sll.h"
/*
* Adds new at ref so that (*ref) points to new and
* its "next" points the "old ref".
* */
void sll_add_node(struct sll_node **ref, struct sll_node *new)
{
new->next = (*ref);
*ref = new;
}
struct sll_node *sll_add(struct sll_node **ref)
{
struct sll_node *new = SLL_NEW_NODE;
sll_add_node(ref, new);
return new;
}
/*
* returns a ref to node found from head having the same key (of length
* sz_key) using memcmp(), returns NULL if not found.
* */
struct sll_node **sll_find(struct sll_node **head,
const void *key, size_t sz_key)
{
struct sll_node **walk;
sll_for_ref(walk, head) {
if ((*walk)->sz_key == sz_key) {
if (memcmp((*walk)->key, key, sz_key) == 0)
return walk;
}
}
return NULL;
}
/*
* returns node if found with the same key (of length sz_key), if not found
* adds a node using sll_add and returns its allocation.
*/
struct sll_node *sll_repl(struct sll_node **head,
const void *key, size_t sz_key)
{
struct sll_node **ref_target;
ref_target = sll_find(head, key, sz_key);
if (ref_target) {
return *ref_target;
} else {
return sll_add(head);
}
}
/* makes (*ref) point to (*ref)->next. Returns removed */
struct sll_node *sll_rm(struct sll_node **ref)
{
struct sll_node *target;
target = (*ref);
(*ref) = (*ref)->next;
return target;
}
/*
* Frees all nodes, their data & key (using free_data and key) from ref.
* *ref assigned to null, returns # of nodes deleted.
* */
size_t sll_rmall(struct sll_node **ref,
void (*free_data)(void *), void (*free_key)(void *))
{
struct sll_node *cur, *next;
size_t delcnt = 0;
for (cur = *ref; cur; cur = next) {
next = cur->next;
if (free_data)
free_data(cur->data);
if (free_key)
free_key(cur->key);
free(cur);
delcnt++;
}
*ref = NULL;
return delcnt;
}