如何在没有计数器变量的情况下在 LinkedQueue.java 中查找队列的大小

How to find size of a queue in LinkedQueue.java without a counter variable

因此,对于一个项目,我必须创建一个 LinkedQueue class 但没有计数器变量,因此我无法准确跟踪队列中有多少元素。 我需要创建一个大小方法来 return 队列中的元素数量,但我不知道该怎么做...这是我的代码:

package animal;
import exceptions.EmptyQueueException;

/**
* @author Sharon Umute 
* Comp 139 001B
*/
public class LinkedQueue<T> implements QueueADT<T>{

SinglyLinkedNode<T> tail,head;

public LinkedQueue(){
    head=tail=null;
}

@Override
public void enqueue(T element) {
    SinglyLinkedNode<T> node =new SinglyLinkedNode<T>(element); 
    if(isEmpty()){
        head = node;
    }else{
        tail.setNext(node);
    }
    tail=node;
}

@Override
public T dequeue() throws EmptyQueueException {
    if (isEmpty()){
        throw new EmptyQueueException("queue");
    }else{
        T result = head.getElement();
        head=head.getNext();

        if(isEmpty()){
            tail=null;
        }
        return result;
    }
}

@Override
public T first() throws EmptyQueueException {
    if (isEmpty()){
        throw new EmptyQueueException("queue");
    }else{
        T result=head.getElement();
        return result;
    }
}

@Override
public boolean isEmpty() {
    return(head.getElement()==null);
}

@Override
public int size() {

}

}

我认为这应该是实现大小方法的好方法:

   Iterator it = this.head.iterator();
   int i = 0;

    while (it.hasNext())
    {
       LinkedQueue node = it.Next();
       i++;
    }
    return i;