Пример #1
0
int SLInsert(SortedListPtr list, void *newObj)
{
	// Create node cast link as a self referential node
	SortedNodePtr newItem = malloc(sizeof(struct SortedNode));

	// Set new item values
	newItem->value = newObj;
	newItem->count = 1;
	newItem->link = NULL;
	
	// Temp node to traverse through list
	SortedNodePtr current = list->head;

	// Insert
	if(current == NULL)
	{
		// Point to new item and increment size of list
		list->head = newItem;
		list->counter++;

		return 1;
	}
	else
	{
		if(list->compare(current->value, newObj) != 0)
		{
			if(list->compare(current->value, newObj) < 0)
			{
				// Add new item to front
				newItem->link = list->head;
				list->head = newItem;

				//Increment size of list
				list->counter++;

				return 1;
			}

			// Sort and add
			sort(list, newItem);

			return 1;
		}
	}

	// ERROR
	free(newItem);
	return 0;
}
Пример #2
0
int SLRemove(SortedListPtr list, void *newObj)
{
	SortedNodePtr current = list->head, previous = NULL;

	while(current->link != NULL && list->compare(current->value, newObj) != 0)
	{
		// Store current node into previous
		previous = current;

		// Move to next node
		current = current->link;
	}

	// Only remove if count on node is one or lower
	if(previous == NULL && current->count <= 1)
	{
		list->head = current->link;
		list->destruct(current->value);
		free(current);
		
		// Decrement list size
		list->counter--;

		return 1;
	}
	else if(current->count <= 1)
	{
		// Previous points to node after the one being deleted
		previous->link = current->link;

		// Free the memory
		list->destruct(current->value);
		free(current);

		// Decrement list size
		list->counter--;

		return 1;
	}
	else
	{
		// Make reference count go down by one
		current->count--;
	}

	// Couldn't remove
	return 0;
}