Originally Posted by
andrewh
I think I see what you mean. The pointer has advanced to node 3 at the
end of the program and if I want to access the node 2, I have to do reverse
direction to the pointer to get the data in 2nd node.
Here how they:
1st node: root->next
root->x
2nd node: conductor->next
conductor->x
3rd node: conductor->next
conductor->x
As you noticed at the end of the program, I was able to read the data of the 1st node. I guess this because the pointer was unique. If we have to name every pointer a unique name then, that would not be practical. I would to be able to
read the 2nd node when I have traversed to the end of the above link list.
I guess the question is: How do I travel in reverse on pointers?
Thanks again,
Andrew
Well, first I'm not sure what your saying but here is the basic concept of your list.
root is the head or the first node of your list.
You then set conductor to point to root( the head of the list).
The only purpose of the conductor is to traverse the list so you can access elements other than the head.
Now for your question,
How do I travel in reverse on pointers?
There is no way to reverse the direction of a pointer in c++. But you can get you desired effect by adding a previous pointer to the list.
Code:
struct node
{
int x;
node *next;
node *prev;
};
this is known as a doubly linked list.
Now you can rebuild your list like this
Code:
node *root;
node *conductor;
root = new node;
root->next = 0;
root->prev = 0;
root->x = 12;
cout<< "The Root Node Value is = " << root->x <<endl;
conductor = root;
Now when you add a new node, you just have to link the previous pointer as well -
Code:
//=======================================================
// 2nd Node Geneartion
//=======================================================
conductor->next = new node;
conductor = conductor->next;
conductor->next = 0;
conductor->prev = root;
conductor->x = 42;
cout<< "The 2nd Node Value of X is = " << conductor->x <<endl;
Now you, have access to both the previous and next node in the list and the ability to walk the list in both directions.