Counting a list iteratively
This is a simple way of counting elements in a list. For some, they would prefer to embed this operation upon list creation and insertion or deletion.
int count_it(LINK head)
{
int cnt = 0;
for ( ; head != NULL; head = head -> next)
++cnt;
return cnt;
}

for the purpose of learning the implementation you did is quite correct.
and yes. you are correct. a better approach would be to actually _track_ the growth of the list on the fly. (insertion/deletion)
like so:
typedef struct {
LINK HEAD; /* start node */
LINK TAIL; /* end node */
int size; /* number of nodes */
};
this minimizes the linear running time overhead of doing a loop-implemented traversal everytime we wanna know the size of a particular linked list.
Comment by amerei — November 20, 2005 @ 10:09 am