-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list.c
79 lines (69 loc) · 1.5 KB
/
linked_list.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
#include "linked_list.h"
#include <assert.h>
void List_init(ListHead* head) {
head->first=0;
head->last=0;
head->size=0;
}
ListItem* List_find(ListHead* head, ListItem* item) {
// linear scanning of list
ListItem* aux=head->first;
while(aux){
if (aux==item)
return item;
aux=aux->next;
}
return 0;
}
ListItem* List_insert(ListHead* head, ListItem* prev, ListItem* item) {
if (item->next || item->prev)
return 0;
#ifdef _LIST_DEBUG_
// we check that the element is not in the list
ListItem* instance=List_find(head, item);
assert(!instance);
// we check that the previous is inthe list
if (prev) {
ListItem* prev_instance=List_find(head, prev);
assert(prev_instance);
}
// we check that the previous is inthe list
#endif
ListItem* next= prev ? prev->next : head->first;
if (prev) {
item->prev=prev;
prev->next=item;
}
if (next) {
item->next=next;
next->prev=item;
}
if (!prev)
head->first=item;
if(!next)
head->last=item;
++head->size;
return item;
}
ListItem* List_detach(ListHead* head, ListItem* item) {
#ifdef _LIST_DEBUG_
// we check that the element is in the list
ListItem* instance=List_find(head, item);
assert(instance);
#endif
ListItem* prev=item->prev;
ListItem* next=item->next;
if (prev){
prev->next=next;
}
if(next){
next->prev=prev;
}
if (item==head->first)
head->first=next;
if (item==head->last)
head->last=prev;
head->size--;
item->next=item->prev=0;
return item;
}