print function in circular list

my code dousn't print members of any object
i try another code
it print all members but
will fall in infinite loop...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void LED::print()
{

	if(head=NULL)
		{cout<<"Empty List"<<endl;
	return;
	}
	nodeptr out=head;
	for(int i=1;i<this->cot();i++)
	{
		cout<<out->data<<endl;
		out=out->link;

	}

}
/*////////////////////////*/
int LED::cot()
{
nodeptr temp=head;
int c=0;
if(head==NULL)
	return 0;
else
	c++;
while(temp->link!=head)
{
c++;
temp=temp->link;

}
return c;


}


Last edited on
I am no expert in this, but it sounds like you need a sentinel variable in the node class (or struct), which is set in the head node, and each node is checked to see if the sentinel is set, so to prevent infinite traversal .


HTH
In your LED::print() method, your if statement is incorrect. You're using a single =, which assigns the value NULL to head. Since NULL is equivalent to 0, the expression (head=NULL) evaluates to zero, i.e. false.

You don't show the definition of head, but assuming it's a global variable:

When you call LED::cot(), head has been set to NULL, so it returns 0.

In your for loop you initialise i to 1, and since cot() returns 0, the condition i < this->cot() is never true, so it never enters the loop. Thus nothing is ever output.

You need to change the if statement to use the equality comparison operator, ==.
Last edited on
thanks

i changed if statment :)

but still the last node doesn't appear

ie:

INPUT:
9
6
8
5
7
4
5
3

OUTPUT:
9
6
8
5
7
4
5

closed account (D80DSL3A)
Maybe i should start at 0 in the for loop in print().

I would not use the cot() and replace the for loop in print() with:
1
2
3
4
5
6
nodeptr out=head;
do
{
	cout<<out->data<<endl;
	out=out->link;
}while( out != head );
Last edited on
thanks
it's work :)
Topic archived. No new replies allowed.