[ create a new paste ] login | about

Link: http://codepad.org/eOqb8tH6    [ raw code | fork ]

C, pasted on Jun 8:
#include <stdio.h>
#include <stdlib.h>

typedef int TYPE;

typedef struct node
{
	TYPE data;
	struct node *next;
} node

//Acho que os nomes das funções são bem explicativos...
void add_node(node** root, TYPE value);
void remove_node(node** root, node* n);
node* find_node(node* root, TYPE value);
void destroy_list(node** root);
void print_list(node* root);
	

int main()
{
node* list = NULL;
	
	add_node(&list, 1);
	add_node(&list, 2);
	add_node(&list, 3);
	add_node(&list, 4);
	add_node(&list, 5);
	add_node(&list, 6);
	add_node(&list, 7)
	add_node(&list, 8);
	add_node(&list, 9);
	
	print_list(list);
	
	fprintf(stdout, "\nVamos agora apagar alguns nós (7 e 8)...\n\n");
	
	remove_node(list, find_node(list, 7));
	remove_node(&list, find_node(list, 8));
	
	print_list(list);
	
	fprintf(stdout, "\nVamos liberar a lista inteira...\n\n");
	
	destroy_list(&list);
	
	fprintf(stdout, (list == NULL)?("Lista liberada\n"):("algo correu mal...\n"));
	
	return 0;

}

void add_node(node** root, TYPE value)
{
	if ((*root) == NULL)
	{
		(*root) = (node*)malloc(sizeof(node));
		(*root)->data = value;
		(*root)->next = NULL;
		return;
	}
	
node *curr = (*root);
node *newnode = (node*)malloc(sizeof(node));

	newnode->data = value;
	newnode->next = NULL;
	
	while (curr->next != NULL)
		curr = curr->next;
		
	curr->next = newnode;
}

void remove_node(node** root, node* n)
{
node *curr = (*root);

	if (n == NULL)
		return;

	if ((*root) == n)
	{	
		(*root) = (*root)->next;
		free(curr);
		return;
	}
	
	while (curr->next != n)
	{
		if (curr = NULL)
		{
			fprintf(stderr, "Node: not found in the list\n");
			return;
		}
		
		curr = curr->next;
	}
	
	curr->next = n->next;
	
	free(n);
}

node *find_node(node* root, TYPE value)
{
node *curr = root;
	
	for (;; curr = curr->next)
	{
		if (curr->data == value)
			return curr;
		
		if (curr == NULL)
		{
			fprintf(stderr, "value: %d not found in the list\n", value);
			return NULL;
		}
	}
}

void destroy_list(node** root)
{
node *curr = root;

	while (curr != NULL)
	{
		curr = (*root);
		(*root) = (*root)->next;
		
		free(curr);
	}
}

void print_list(node* root)
{
node *curr = root;

	while (curr != NULL)
	{
		fprintf(stdout, "[%x] %d\n", curr, curr->data);
		curr = curr->next;
	}
}


Create a new paste based on this one


Comments: