C doesn't exist when
D is created, so the value of
D.next is wrong as soon as
C is created. You can traverse from
D back to
C and so on because the pointer
D really does point to the object when you construct
C.
Personally I'd make
list a class and give it an
add(int) member function:
1 2 3 4 5 6
|
node * list::add( int i )
{
node *n = new node( tail, i, NULL ) ;
tail.next = n ;
return n ;
}
|
I guess this might also work too:
1 2 3 4 5 6
|
node * addToList( list l, int i )
{
node *n = new node( list.tail, i, NULL ) ;
list.tail.next = n ;
return n ;
}
|
It may also be helpful to construct the list as a
ring, such that you have only one "top" node that points at both the first and last data nodes, rather than a head and tail that point off the ends into NULL space. In such a structure, when you need to traverse "the whole list", your loop conditions are concerned only with whether you've gone around the whole ring and have returned to the top:
|
for( node *n = top->next ; n != top ; n = n->next )
|
The termination test is comparing a pointer to another pointer, not the "equality" of objects, so there's no nervousness about using the basic
!= operator.