How do you count the number of elements in the circular linked list?

How do you count the number of elements in the circular linked list?
A.
Code:
public int length(Node head)
{
	int length = 0;
	if( head == null)
		return 0;
	Node temp = head.getNext();
	while(temp != head)
	{
		temp = temp.getNext();
		length++;
	}
	return length;
}
B.
Code:
public int length(Node head)
{
	int length = 0;
	if( head == null)
		return 0;
	Node temp = head.getNext();
	while(temp != null)
	{
		temp = temp.getNext();
		length++;
	}
	return length;
}
C.
Code:
public int length(Node head)
{
	int length = 0;
	if( head == null)
		return 0;
	Node temp = head.getNext();
	while(temp != head && temp != null)
	{
		temp = head.getNext();
		length++;
	}
	return length;
}
D.
Code:
public int length(Node head)
{
	int length = 0;
	if( head == null)
		return 0;
	Node temp = head.getNext();
	while(temp != head && temp == null)
	{
		temp = head.getNext();
		length++;
	}
	return length;
}
 

Tìm kiếm

Back
Top