I need to return the size of a doubly linked list and I am having trouble thinking of the logic to go about doing this.


template <class T>
int List<T>::size() const

Returns the current size of the list; i.e., the number of data items currently stored in the list. Since the size has not been stored as a data member, you will need to traverse the list and count the number of nodes, and then return that count.

Anything to get me started on this would be great.

Thank You

Recommended Answers

All 8 Replies

Ya everything I came across says to do that but thats not what the assignment calls for...

what would be the basic logic for that? thats where i'm gettin stumped i know i need to loop but i'm drawin a blank from there

This is where I'm at right now, am I at least headed in the right direction? I'm stuck at this point.

template <class T>
      int List<T>::size() const
      {
      int count;
      LNode<T>* ptr;
      
      if(ptr == NULL)
             return 0;
      else
             {

Any suggestions I've still been playing with this without any luck so anything would be great.

LNode<T>* ptr;

The above line doesn't give ptr a value. Therefore it could be anything. It could be NULL. It could be Oxeff34. It could be 99. Who knows. The problem is you check to see if it is NULL in the very next line.

if(ptr == NULL)

Before you check ptr against a value you need to give it a meaningful value. You could do that with initialization or with assignment. A reasonable value to give it would be the first node of the list, whatever that is called.

Better yet, declare the first node of the list to be NULL when you create the list. Then evaluate that node when you want to determine if the list is empty. For example:

struct listNode
{
    listNode * next;
};
struct List
{
   listNode * firstNode;
   List () : firstNode(NULL){};
   int size()
   {
      int count = 0;
      if(firstNode == NULL)
        //this list is empty
      else----fill the rest of this out as you need to.
   }
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.