Print number of nodes in a list

Asked

Viewed 153 times

2

This code below does not work properly, I type 5 knots and was to return the number 5 (total amount of knots entered). It happens that returns me 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 mistake is on the line of while, I’m not sure.

It’s decreasing, I think when I point to the next one it automatically decreases in total.

2 answers

3


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

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

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

  • 1

    So it’s always going to be like this: is Prox going to have NULL value? Talking about this code there, because this is wrong. Loop stops in NULL and is not counted at the end?

  • 1

    'Cause you’re telling me to do it. There’s nothing wrong, it’s just math.

  • 1

    I managed to return the correct quantity here, removed the '-> Prox' and compiled return correctly now.

  • 1

    It is a solution, I only have my doubts if you will always do everything you want. I can’t even say because I don’t know what you want.

0

Just modify

while (aux -> prox != NULL)

for

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.