-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn_list_remove_nth.c
More file actions
54 lines (37 loc) · 882 Bytes
/
n_list_remove_nth.c
File metadata and controls
54 lines (37 loc) · 882 Bytes
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
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "n_list_int.h"
void *n_list_remove_nth(tn_list *l, int nth)
{
void *data;
if (l->head == NULL) {
trurl_die("n_list_remove_nth: remove from empty list\n");
return NULL;
}
if (nth < 0 || l->items <= nth) {
trurl_die("n_list_remove_nth: index(%d) out of bounds(%d)\n", nth,
l->items);
return NULL;
}
if (nth == 0) {
data = n_list_shift(l);
} else if (nth == l->items - 1) {
data = n_list_pop(l);
} else {
register struct list_node *node, *prev_node;
register size_t n = 0;
for (prev_node = l->head, node = l->head->next; node != NULL;
prev_node = node, node = node->next) {
n++;
if (n == (size_t) nth)
break;
}
n_assert(node != NULL);
l->items--;
prev_node->next = node->next;
data = node->data;
free(node);
}
return data;
}