-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedList.c
115 lines (99 loc) · 2.11 KB
/
linkedList.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdlib.h>
#include "linkedList.h"
#define DONE 1
Node* create_node(void *data) {
Node *n = malloc(sizeof(Node));
n->data = data;
n->next = NULL;
return n;
}
LinkedList createList(void) {
LinkedList list;
list.head = NULL;
list.tail = NULL;
list.count = 0;
return list;
}
int add_to_list(LinkedList *list,Node *node) {
if(!node) return 0;
if(list->tail == NULL) {
list->head = node;
list->tail = node;
} else{
list->tail->next = node;
list->tail = node;
}
list->count++;
return DONE;
}
void* get_first_element(LinkedList list) {
if(!list.head) return NULL;
return list.head->data;
}
void* get_last_element(LinkedList list) {
if(!list.head) return NULL;
return list.tail->data;
}
int parseInt(void *ref){
return *(int*)(ref);
}
char* parseString(void *ref){
return *(char**)(ref);
}
void traverse(LinkedList list, void (*operation)(void *data)) {
Node *walker = list.head;
while(!walker){ operation(walker->data); }
}
void* getElementAt(LinkedList list, int index) {
Node *walker = list.head;
int i;
if(index >= list.count || index < 0) return NULL;
for (i = 1; i <= index; ++i) {
walker = walker->next;
}
return walker->data;
}
int indexOf(LinkedList list, void *element) {
// Node *walker = list.head;
// int i;
// while(!walker) {
// walker->data
// }
}
Node* getNodeAt(LinkedList list, int index){
Node *walker = list.head; int i;
if(index < 0 || index >= list.count) return NULL;
for (i = 1; i <= index; ++i) {
walker = walker->next;
}
return walker;
}
int asArray(LinkedList list, void **result) {
int i;
Node *this;
void **r = malloc(list.count);
for(i=0; i<list.count; ++i){
this = getNodeAt(list,i);
r[i] = this->data;
}
*result = r;
return list.count;
}
void* deleteElementAt(LinkedList *list, int index) {
Node *prev, *next, *this;
prev = getNodeAt(*list, index-1);
next = getNodeAt(*list, index+1);
this = getNodeAt(*list, index);
if(!this) return NULL;
if(list->head == this){
list->head = next;
}
if(list->tail == this){
list->tail = prev;
}
if(index > 0 && index < list->count){
this->next = NULL;
prev->next = next;
}
return this->data;
}