-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLvNode.c
More file actions
114 lines (87 loc) · 1.95 KB
/
LLvNode.c
File metadata and controls
114 lines (87 loc) · 1.95 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
103
104
105
106
107
108
109
110
111
112
113
/*
* Code adapted from:
* The practice of programming/Brian W. Kernighan and Rob Pike,
* Addison-Wesley professional computing series, 1999.
* ISBN 0-201-61586-X
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LLvNode.h"
/*
* llNewNode: create and initialize data
*/
LLvNode *
llNewNode(char *key, void *value)
{
LLvNode *newp;
newp = (LLvNode *) malloc(sizeof(LLvNode));
/* assign data within new node */
newp->key = key;
newp->value = value;
/* make sure we point at nothing */
newp->next = NULL;
return newp;
}
/*
* llAppend: add newp to end of listp
*
* as above, we always return the value that
* should be the new head of the list
*/
LLvNode *
llAppend(LLvNode *listp, LLvNode *newp)
{
LLvNode *p;
if (listp == NULL)
return newp;
for (p = listp; p->next; p = p->next)
;
p->next = newp;
return listp;
}
/*
* llPrepend: add newp to front of list
*
* by returning ourselves, we give back the
* value that should be the new head of the list
*/
LLvNode *
llPrepend(LLvNode *listp, LLvNode *newp)
{
newp->next = listp;
return newp;
}
/* llLookupKey: sequential search for key in listp */
LLvNode *
llLookupKey(LLvNode *listp, char *key)
{
for ( ; listp != NULL; listp = listp->next) {
if (strcmp(key, listp->key) == 0) {
return listp;
}
}
return NULL; /* no match */
}
/* llApplyFn: execute fn for each element of listp */
void
llApplyFn(LLvNode *listp, void (*fn)(LLvNode*, void*), void *arg)
{
for ( ; listp != NULL; listp = listp->next)
(*fn)(listp, arg); /* call the function */
}
/* llFree : free all elements of listp */
void
llFree(LLvNode *listp, void (*userDeleteFn)(LLvNode*, void*), void *arg)
{
LLvNode *next;
for ( ; listp != NULL; listp = next) {
/** hang on to the next pointer */
next = listp->next;
/** call the user function, if provided */
if (userDeleteFn != NULL)
(*userDeleteFn)(listp, arg);
/** free the list node itself */
free(listp);
}
}