fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct lligada {
  5. int valor;
  6. struct lligada *prox;
  7. } *LInt;
  8.  
  9. void addHead (LInt *l, int val){
  10. LInt newHead = malloc(sizeof(*newHead));
  11. newHead->valor = val;
  12. newHead->prox = *l;
  13. *l = newHead;
  14. }
  15.  
  16. void print(LInt list){
  17. LInt curr = list;
  18. while (curr != NULL){
  19. printf("%d -> ", curr->valor);
  20. curr = curr->prox;
  21. }
  22. printf("NULL");
  23. }
  24.  
  25. int removeAll (LInt *l, int x){
  26. int r = 0;
  27. LInt pt = *l, ant = NULL;
  28. while (pt != NULL){
  29. if (pt -> valor == x){
  30. if (ant == NULL){
  31. *l = pt->prox;
  32. }
  33. else {
  34. ant -> prox = pt -> prox;
  35. }
  36. LInt toDelete = pt;
  37. pt = pt -> prox;
  38. free(toDelete);
  39. r++;
  40. }
  41. else {
  42. ant = pt;
  43. pt = pt -> prox;
  44. }
  45. }
  46.  
  47. return r;
  48. }
  49.  
  50. int main() {
  51. LInt list = NULL;
  52. addHead(&list, 10);
  53. addHead(&list, 20);
  54. addHead(&list, 15);
  55. addHead(&list, 10);
  56. addHead(&list, 12);
  57. addHead(&list, 10);
  58. addHead(&list, 10);
  59. addHead(&list, 13);
  60. addHead(&list, 10);
  61.  
  62. print(list);
  63. int removed = removeAll(&list, 10);
  64. printf("\nRemoved nodes: %d\n", removed);
  65. print(list);
  66. }
  67.  
Success #stdin #stdout 0s 4180KB
stdin
Standard input is empty
stdout
10 -> 13 -> 10 -> 10 -> 12 -> 10 -> 15 -> 20 -> 10 -> NULL
Removed nodes: 5
13 -> 12 -> 15 -> 20 -> NULL