
pointers 3
By: a guest on Sep 29th, 2010 | syntax:
C | size: 1.39 KB | hits: 144 | expires: Never
/* Listas ligadas - Exemplo muito simples com as seguintes funções:
- Pesquisa
- Adição de dados
- Remoção de dados
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Lista {
int key;
struct Lista *next;
}List;
List * addList(List *head, int value) {
List *new = (List *) malloc(sizeof(List));
new->key = value;
new->next = NULL;
if(!head) {
head = new;
return head;
}
head->next = new;
return head->next;
}
List *findList(List *head, int value) {
List *find = head;
while(find && find->key != value) {
find = find->next;
}
if(!find) return NULL;
return find;
}
List * deleteList(List *head, int value) {
List *find = head;
List *aux = NULL;
if(head->key == value) {
aux = head->next;
free(head);
return aux;
}
while(find && find->next->key != value) find = find->next;
aux = find->next;
find->next = aux->next;
free(aux);
return head;
}
int main(void) {
List *head = NULL, *tail = NULL;
tail = addList(tail,10);
head = tail;
tail = addList(tail,20);
tail = addList(tail,30);
tail = findList(head,40);
if(tail) printf("Valor encontrado: %i\n", tail->key);
else printf("Valor não encontrado\n");
head = deleteList(head,10);
while(head) {
printf("Value: %i\n", head->key);
head = head->next;
}
return 0;
}