Determining the Length of Linked List

Jul 26, 2011 at 1:02am
I have a linked list in a template class. My function is trying to determine the length of this list, but it gets stuck in an infinite loop. I know that it traces back to the cursor pointer. When I watch the local variables, the IDE shows the value of cursor as "(" and it never changes. It is supposed to start out as the head pointer and iterate through the list until ultimately winding up as NULL. Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    //Create initial node
    D_Node<string> *head_ptr;
    D_Node<string> *tail_ptr;
    string entry = "two";
    dlist_head_insert(head_ptr, tail_ptr, entry);
 
    size_t my_length = dlist_length(head_ptr);

    system("PAUSE");
    return EXIT_SUCCESS;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
	template <class Item>
	size_t dlist_length(const D_Node<Item> *head_ptr)
	{
           const D_Node<Item> *cursor;
           size_t count;
        
           count = 0;
           for (cursor = head_ptr; cursor != NULL; cursor->fore())
	   {
               ++count;
           }
        
	   return count;
	}


Can anybody see what the problem is? Thanks!
Last edited on Jul 26, 2011 at 1:03am
Jul 26, 2011 at 1:07am
Anything wrong with using the existing STL container's linked list .

std::list<std::string> data;
data.size();
Jul 26, 2011 at 1:16am
Thanks. I need to figure out the cursor pointer problem, not only for this immediate purpose, but also for some other functions that I need to write.

Can you tell why (or if) my cursor pointer is failing?
Jul 26, 2011 at 1:19am
(1) Are you sure there is a NULL at the end of the list?
(2) Are you sure your cursor pointer advances properly?
Last edited on Jul 26, 2011 at 1:20am
Jul 26, 2011 at 1:27am
(1) Yes
(2) No. I'm pretty sure that the problem is one of two things. Either I am not getting cursor set up correctly at the beginning, or it is not advancing. The part that says cursor->fore() is suppose to call

1
2
3
4
D_Node<Item>* D_Node<Item>::fore( )
{
   return link_fore;
}


where link_fore is a member variable like this:

1
2
3
4
5
6
7
template <class Item>
class D_Node
{
...
private:
    D_Node *link_fore;
};


Thanks for your help. Any thoughts?
Last edited on Jul 26, 2011 at 1:28am
Jul 26, 2011 at 1:32am
Right. In this case, you need this -> cursor = cursor->fore() instead of just this -> cursor->fore().
Last edited on Jul 26, 2011 at 1:33am
Jul 26, 2011 at 1:35am
I should have seen that one myself.

Thanks again!
Topic archived. No new replies allowed.