Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

snippet concerning circular lists

$
0
0
Hi. Can anyone explain me why do I need the following snippet in main:

// ???? 
        if(element == NULL)
           element = clist_next(clist_head(&list));
        else 
           element = clist_next(element);



void clist_init(CList* list, void (*destroy)(void* data)) {

    list->size = 0;
    list->head = NULL; 
    list->destroy = destroy;
}

// insert a node after the current 
int clist_ins_next(CList* list, CListElmt* element, const void* data) {
    // create a new element
    CListElmt* new_element;
    if((new_element = malloc(sizeof(CListElmt))) == NULL)
        return -1;
    // set the data to the new element
    new_element->data = (void*) data;
    // insert when the list is empty
    if(clist_size(list) == 0)
    {    
      // keep a reference to itself
      new_element->next = new_element;
      list->head = new_element;
    }
    // insert when the list is not empty
    else {
      new_element->next = element->next;
      element->next = new_element;
    }            
    // update the size of the list
    list->size++;
    return 0;
}




int main(void) {
    CList list;
    CListElmt* element;
    int* data;
    int i;

    clist_init(&list, free);
    element = clist_head(&list);
    for (i = 0; i <= 9; i++) {
        if ((data = malloc(sizeof (int))) == NULL)
            return EXIT_FAILURE;
        *data = i;
        if (clist_ins_next(&list, element, data) < 0)
            return EXIT_FAILURE;

        // ???? 
        if(element == NULL)
           element = clist_next(clist_head(&list));
        else 
           element = clist_next(element); 
    }
    print_list(&list);
    return EXIT_SUCCESS;
}


Viewing all articles
Browse latest Browse all 51036

Trending Articles