Print amount of nodes in a list

2

This code below does not work correctly, I type 5 nodes and was to return the number 5 (total number of nodes inserted). It turns out that I get 4.

int qtd_no_lista (tipo_lista * recebida)
{
 tipo_lista * aux = recebida;
 int cont=0;
  while (aux -> prox != NULL)
  {
    aux = aux ->prox;
    cont++;
  }
 printf("A quantidade de nos presente na lista e %d\n",cont);
 return cont;
}

I think the error is in the line of while , not sure, could help me. It's decrementing, I think when I point to the next one it automatically decreases in total. Please explain.

    
asked by anonymous 18.04.2017 / 19:57

2 answers

3

You have to add one manually if you keep this logic. Or you can only start from 1 which is simpler.

The problem is that the last item in the list has the value of prox exactly the value NULL , so the loop will stop on it, it will not be evaluated, so it will not be counted.

And considering the previous question I would do this with for , it would eliminate at least 4 lines.

    
18.04.2017 / 20:02
0

Just change

while (aux -> prox != NULL)

by

while (aux != NULL)

* Note: The rest is correct, do not change the counter to start at 1 because it will return a wrong value if you pass an empty list.

    
18.04.2017 / 21:20