Пример #1
0
int SLRemove(SortedListPtr list, void *newObj)
{
												//If there is no data in the list, or no data at the head node, 
    if(!list || list->head == NULL || !newObj){	//or no data in the new object, nothing to remove.
        return 0;
    }		

    Node *ptr = list->head;
    Node *prev = NULL;
    while(ptr != NULL){
        if(list->cf(ptr->data, newObj) == 0){ //If the Object we are looking to remove is the head node
            if(prev == NULL){   				//Remove the head node and have the node that comes after take its place
                list->head = list->head->next;
                if(list->head){
                    list->head->counter++;     //increment counter so the SortedListPtr is pointing to the new head
                }
                ptr->counter--;    
                ptr->moveRef = 1;
                if(ptr->counter <= 0){     
                    list->df(ptr->data);	//If no object is found at the current node, destroy it.
                    if(ptr->next !=NULL){   
                        ptr->next->counter--;  //If there is a ptr to the next node, decrement the reference counter
                    }
                    free(ptr);				//Free the memory at the ptr if there was no data in the node
                    return 1;
                }
            }
            else{
                prev->next = ptr->next;     //If we do not delete the head node, we must find the node we need to delete
                if(ptr->next != NULL){      //If we are at the current node and it is not what we are looking for,
                    ptr->next->counter++;	//and the node has a next, we increment reference counter and go to the next node
                    ptr->counter--;
                    ptr->moveRef = 1;
                }
                if(ptr->counter <=0){
                    list->df(ptr->data);
                    if(ptr->next != NULL){
                        ptr->next->counter--;
                    }
                    free(ptr);
                    return 1;
                }
            }
        }
        prev = ptr;
        ptr = ptr->next;
    }
    return 0;
}
Пример #2
0
void SLDestroy(SortedListPtr list)
{
    if(!list){
        return;
    }
	//As long as the list is still exsistant, iterate through destroying all node data.
    Node *ptr = NULL;	//Ptr to the node now points to null
    while(list->head != NULL){
        list->df(list->head->data);			//Use the destroy function
        ptr = list->head;
        list->head = list->head->next;		//The new head of the list is the next node
        free(ptr);						//free the memory that was allocated for the node ptr
    }
    free(list);				//Free the memory that was allocated for the list
}