-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedList.c
More file actions
117 lines (96 loc) · 2.29 KB
/
SortedList.c
File metadata and controls
117 lines (96 loc) · 2.29 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
114
115
116
117
#include "SortedList.h"
#include <string.h>
#include <stdio.h>
void SortedList_insert(SortedList_t *list, SortedListElement_t *element){
if(list == NULL || element == NULL){
fprintf(stderr, "One of the arguments is null.\n");
return;
}
//if not head only
SortedListElement_t *current = list;
const char *key = element->key;
while(current->next != NULL && (strcmp(current->next->key, key) < 0)){
current = current->next;
}
element->next = current->next;
element->prev = current;
if(opt_yield & INSERT_YIELD){
sched_yield();
}
if(element->next != NULL){
element->next->prev = element;
}
current->next = element;
}
int SortedList_delete(SortedListElement_t *element){
if(element == NULL){
fprintf(stderr, "Argument is null.\n");
return 1;
}
if(element->prev != NULL){
if(element->prev->next != element){
fprintf(stderr, "Corrupted pointers.\n");
return 1;
}
}
if(element->next != NULL){
if(element->next->prev != element){
fprintf(stderr, "Corrupted pointers.\n");
return 1;
}
}
element->prev->next = element->next;
if(opt_yield & DELETE_YIELD){
sched_yield();
}
if(element->next != NULL){
element->next->prev = element->prev;
}
return 0;
}
SortedListElement_t *SortedList_lookup(SortedList_t *list, const char *key){
//null argument check
if(list == NULL || key == NULL){
fprintf(stderr, "One of the arguments is null.\n");
return NULL;
}
//iterate and attempt to find
SortedListElement_t *current = list->next;
while(current != NULL){
if(strcmp(current->key,key) == 0){
return current;
}
else{
if(opt_yield & LOOKUP_YIELD){
sched_yield();
}
current=current->next;
}
}
return NULL;
}
int SortedList_length(SortedList_t *list){
if(list == NULL){
fprintf(stderr, "Argument is null.\n");
return -1;
}
SortedListElement_t *current = list->next;
int count = 0;
while(current != NULL){
//check for corruption
if(current->prev->next != current){
return -1;
}
else if(current->next != NULL && current->next->prev != current){
return -1;
}
else{
count++;
if(opt_yield & LOOKUP_YIELD){
sched_yield();
}
current=current->next;
}
}
return count;
}