Exemplo n.º 1
0
LIST_TYPE list_remove(int index, List *list){
	if(index >= list->size || index < 0){
		printf("index is out of bounds.\n");
		assert(0);
		return NULL;
	}
	if(list->size == 1){
		list->head == NULL;
		list->tail == NULL;
		list->size--;
		return NULL;
	}
	if(index == 0){
		return list_removeFirst(list);
	}
	else if(index == list->size-1){
		return list_removeLast(list);
	}
	else{
		int counter = 0;
		Node* ptr;
		for(ptr = list->head; ptr != NULL; ptr = ptr->next){
			if(counter == index){
				Node* left = ptr->prev;
				Node* right = ptr->next;
				left->next = right;
				right->prev = left;
				list->size--;
				return ptr;
			}
			counter++;
		}
        return NULL;
	}
}
Exemplo n.º 2
0
void exampleList()
{
	// Use pooling for efficiency, if you don't want to use pooling
	// then comment out this line.
	pool_list(16);

	List* L = newList();

	list_add(L, "a");
	list_add(L, "b");
	list_add(L, "c");
	list_add(L, "d");
	list_add(L, "e");
	list_add(L, "f");
	
	// Display the current list
	displayStrings(L);		//ABCDEF

	// Remove first item
	list_removeFirst(L);
	displayStrings(L);		//BCDEF
	
	// Add first item back
	list_addFirst(L, "a");
	displayStrings(L);

	list_clear(L);
	if (list_isEmpty(L))
		printf("List was cleared.\n");

	// Add some strings and remove all that begin with -
	int nums[] = {1, 2, 3, 4, 6, 7, 8};
	int x;
	for (x = 0; x < 7; x++)
		list_add(L, &nums[x]);

	displayIntegers(L);

	list_start(L);
	while (list_hasNext(L))
	{
		// get does not move the current node
		x = *((int*)list_peek(L));
		if (x % 2 == 0)
			// remove will remove the node from the list altogether and
			// return the data removed.
			list_remove(L);
		else
			// next will just goto the next node and return the data.
			list_next(L);
	}
	
	// Print out the odd numbers
	displayIntegers(L);

	// Try removing all while traversing
	list_start(L);
	while (list_hasNext(L))
		list_remove(L);
	
	displayIntegers(L);

	if (L->first == NULL && L->last == NULL && L->size == 0)
		printf("All cleaned up!\n");

	// Traverse through an array of strings and find any that start
	// with . and after it add 0 and add one before it that is -
	list_add(L, ".1");
	list_add(L, " two ");
	list_add(L, ".3");
	list_add(L, " four ");
	list_add(L, ".5");

	displayStrings(L);
	
	list_start(L);
	char* c;
	while (list_hasNext(L))
	{	
		c = (char*)list_peek(L);

		if (c[0] == '.')
		{
			list_insertBefore(L, "-");
			list_insertAfter(L, "0");
		}

		list_next(L);
	}
	displayStrings(L);

	char* first = (char*)L->first->data;
	char* last = (char*)L->last->data;
	if (first[0] == '-' && last[0] == '+')
		printf("Insertions correct.\n");

	// This will clear the list of any nodes and pool them and then free
	// the list itself from memory
	list_free(L);
	
	// If you're not using pooling this can be commented out. This will
	// free all pooled nodes from memory. Always call this at the end 
	// of using any List.
	unpool_list();
}