Well, first of all, your node creation should look like this:
node * root = new node(NULL);
If I were you, I'd make a linked list class, as well as a node class.
Something like this:
Code:
class LinkedList{
public:
LinkedList();
~LinkedList();
void AddNode(LinkedListNode);
void DeleteNode(LinkedListNode *);
LinkedLinstNode * GetCurrentNode();
void Start(); //sets current to the first node
void End(); //sets current to the last node
bool IsValid(); //does current point to a valid node?
void Next(); //current points to next node
void Prev(); //current points to previous node
private:
LinkedListNode * begin; // first node, or NULL if none exist
LinkedListNode * end; //last node, or NULL if none exist
LinkedListNode * current;
};
Then, it's easy to iterate through the list, as much as you want.
Code:
for (list.Start();list.IsValid();list.Next()){
//do whatever for each node
}
Note that with this, you will need to always check IsValid() before using a node, as current is allowed to be null if you move off the end of the list. This is an effective way to do stop conditions. Every function that operates on current should check for NULL too.
As another note, you should make the LinkedListNode have a pointer to the LinkedList that it is a part of -- this is for error checking. It's nice and easy to delete a linked list node from a list, without scanning the list, simply by using the prev and next pointers -- but it should check to make sure the node is a member of that list.
So, this should not do anything:
(listA and listB are each LinkedList objects)
listA.DeleteNode(listB.GetCurrentNode());
So the deleteNode function should "know" that the node passed to it was from another linked list, not this one. Also, AddNode should add a copy of the node passed, so someone couldn't pass a node that was already in the list and cause a loop or a break in the list -- a new node should be built internally, and the data copied from the node passed in, which should be unchanged.