Digital Stronghold - Software Engineering Blog




November 19, 2005

Counting a list iteratively

Filed under: Progressive Studies

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;
}

1 Comment »

The URI to TrackBack this entry is: http://eradicus.blogsome.com/2005/11/19/counting-a-list-iteratively/trackback/

  1. 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

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Theme designed by Joset Anthony Zamora


Digital Stronghold

↑ Get Headline Animator