Hi. I need help with my size method. I am using a single-linked list. I tested my code and it returns 0 all the time.

/** This method returns the size of the current list.    <br>
     *  If the current list has no elements,it is empty.     <br>
     *  
     *  @return  size of the current list*/
    public int size() {
        //A counter to keep track of the elements in the list
        int listCounter = 0;
        //initialize the first element as head
        Node<T> node = head;
        //if node is null, then the list is empty
        //and an empty list has 0 elements
        if (node == null) return 0;
        //While the node is not on its last element,
        while(node != null) {
            //increment listCounter
            listCounter ++;
            //node becomes the next node
            node = node.next;   
        }
        //return counter after
        return listCounter;

    }

Usually, the size is a member variable of the class. It would be set to 0 on construction (with no member nodes), incremented when a new node is added, and decremented when one is removed. If you don't do that, then the size() method would have to traverse the entire list to get the number of nodes, and that could be VERY expensive!

The code you gave looks valid and correct. I would look at the other methods in the class to see if they are correct. In particular, I would check to see if the 'head' field is set properly when the first item is added to the list.

(And once it's working, you might find that the "if (node == null) return 0;" line is kind of pointless.)

You want to see the constructor?. I think it's my add method and remove method. I guess im not incrementing right.

Your problem is trivial and occurs at line 12. At this point you test for the end of the list and exit the method but instead of returning the count, you return 0 and get 0 every time as the result!

12 if (node == null) return listcounter;

Line 12 only returns 0 if the head node is null, ie the list is empty. That looks OK to me. In fact I agree with JeffGrigg (above) 100%

SO line 12, I messed up. i should say if head == null then return 0. Not if node == null. Ok thanks. lIll try it.

NO - it's not messed up. The previous line is
Node<T> node = head;
so it makes no difference whether you use head or node in the if test, they both have the same value.

The only thing is that you don't actually need it at all - you can omit it and if head (or node) is null you will drop straight through the while loop and return zero anyway.

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.