ListRet list_insert(TinyList *thiz, size_t index, void *data) { TinyListNode *node = NULL; TinyListNode *cursor = NULL; if((node = list_node_create(data)) == NULL) { return LIST_RET_FAIL; } if(thiz->first == NULL) { thiz->first = node; return LIST_RET_OK; } cursor = list_get_node(thiz, index, 1); if(index < list_length(thiz)) { if(thiz->first == cursor) { thiz->first = node; } else { cursor->prev->next = node; node->prev = cursor->prev; } node->next = cursor; cursor->prev = node; } else { cursor->next = node; node->prev = cursor; } return LIST_RET_OK; }
int list_find_free_pos(List *l) { int i; for (i=0; i<(l->size); i++) if ( list_get_node(l, i)->occupied==0 ) return i; return -1; }
ListRet list_set_by_index(TinyList *thiz, size_t index, void *data) { TinyListNode *cursor = list_get_node(thiz, index, 0); if(cursor != NULL) { cursor->data = data; } return cursor != NULL ? LIST_RET_OK : LIST_RET_FAIL; }
int list_pop_back(List* l) { int last = l->head, last2 = -1; if (list_is_empty(l)) return 0; while (list_get_node(l, last)->next>=0) { last2 = last; last = list_get_node(l, last)->next; } list_get_node(l, last)->occupied = 0; if (last2>=0) list_get_node(l, last2)->next = -1; else { list_get_head(l)->occupied = 0; l->head = -1; } --l->total; return 1; }
int list_delete_at(List *l, int pos) { int i; int at = l->head, pat; if (list_is_empty(l)) return 0; if (pos==0) return list_pop_front(l); for (i=0; i<pos; i++) { pat = at; at = list_get_node(l, at)->next; if (!at && i!=pos-1) return 0; } list_get_node(l, pat)->next = list_get_node(l, at)->next; list_get_node(l, at)->occupied = 0; return 1; }
ListNode* list_create_node(List *l, int data, int next, int *position) { int free_pos = list_find_free_pos(l); ListNode *node = list_get_node(l, free_pos); if (position) *position = free_pos; if (node) { node->data = data; node->next = next; node->occupied = 1; } return node; }
int list_insert_at(List *l, int pos, int data) { ListNode *node; int i, position; int at = l->head, pat; if (pos==0) return list_push_front(l, data); for (i=0; i<pos; i++) { pat = at; at = list_get_node(l, at)->next; if (at<0 && i!=pos-1) return 0; } node = list_create_node(l, data, at, &position); if (node) list_get_node(l, pat)->next = position; ++l->total; return node!=NULL; }
ListRet list_delete(TinyList *thiz, size_t index) { TinyListNode *cursor = list_get_node(thiz, index, 0); if(cursor != NULL) { if(cursor == thiz->first) { thiz->first = cursor->next; } if(cursor->next != NULL) { cursor->next->prev = cursor->prev; } if(cursor->prev != NULL) { cursor->prev->next = cursor->next; } list_node_destroy(cursor); } return LIST_RET_OK; }
ListNode* list_get_next(List *l, ListNode *node) { return list_get_node(l, node->next); }
ListNode* list_get_head(List *l) { return list_get_node(l, l->head); }