Initializing pointers in a doubly linked list

What is wrong with my code?

1
2
3
4
5
6
7
8
9
10
11
12
13
struct node {
  node *prev;  int d;  node *next;
  node(node*p,int i,node *n):prev(p),d(i),next(n){}
};

struct list { node *head; node *tail; };

node *D,*C,*B,*A;

D=new node(NULL,4,C);  
C=new node(D,3,B);  
B=new node(C,2,A);  
A=new node(B,1,NULL);


Pointers (node *) seem to be correctly initialized.
I can traverse from tail (node A) to head (node D) using pointers->previous; but not the other way (from D to A).

Why are the next pointers not correct? I'm assuming there's something fundamentally wrong in my code?
The statements execute in order.
Are you saying in Line10 the value of pointer C is not defined yet, since C is initialized in Line11?
You are using the old value, yes.
So what does Line8 do?
Can you suggest a solution?
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.
Topic archived. No new replies allowed.