Guest

pointers 3

By: a guest on Sep 29th, 2010  |  syntax: C  |  size: 1.39 KB  |  hits: 144  |  expires: Never
download  |  raw  |  embed  |  report abuse
This paste has a previous version, view the difference. Copied
  1. /* Listas ligadas - Exemplo muito simples com as seguintes funções:
  2.    - Pesquisa
  3.    - Adição de dados
  4.    - Remoção de dados
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. typedef struct Lista {
  11.   int key;
  12.   struct Lista *next;
  13. }List;
  14.  
  15. List * addList(List *head, int value) {
  16.   List *new = (List *) malloc(sizeof(List));
  17.   new->key = value;
  18.   new->next = NULL;
  19.   if(!head) {
  20.      head = new;
  21.      return head;
  22.   }
  23.   head->next = new;
  24.   return head->next;
  25. }
  26.  
  27. List *findList(List *head, int value) {
  28.   List *find = head;
  29.   while(find &amp;&amp; find->key != value) {
  30.      find = find->next;
  31.   }
  32.   if(!find) return NULL;
  33.   return find;
  34. }
  35.  
  36. List * deleteList(List *head, int value) {
  37.   List *find = head;
  38.   List *aux = NULL;
  39.   if(head->key == value) {
  40.      aux = head->next;
  41.      free(head);
  42.      return aux;
  43.   }
  44.   while(find &amp;&amp; find->next->key != value) find = find->next;
  45.   aux = find->next;
  46.   find->next = aux->next;
  47.   free(aux);
  48.   return head;
  49. }
  50.  
  51. int main(void) {
  52.   List *head = NULL, *tail = NULL;
  53.   tail = addList(tail,10);
  54.   head = tail;
  55.   tail = addList(tail,20);
  56.   tail = addList(tail,30);
  57.   tail = findList(head,40);
  58.   if(tail) printf("Valor encontrado: %i\n", tail->key);
  59.   else printf("Valor não encontrado\n");
  60.   head = deleteList(head,10);
  61.   while(head) {
  62.     printf("Value: %i\n", head->key);
  63.     head = head->next;
  64.   }
  65.   return 0;
  66. }