When I faced this problem, I came up with two choices.
The First one is to declare the Node structure inside the List class. It's just like:
class List
{
private:
struct Node
{
int data;
Node* next;
}
Node* head;
//...
public:
//....
}
For this one, it works good. Functions in public area can make use of all the elements in Node structure to do insert, delete and so on. Also, this prevent user from directly using the Node structure(I think if we declare Node inside List, others cannot make use of this structure. Is it true?). However, if this Node is very general and will be used also by Stack, Queue and so on, we have to declare it every time. It's inconvenient. Also, if I want to implement some algorithms which works on List(e.g sort), is it possible to do this without even making use of the Node structure?
The second choice is to implement a Node class:
class Node
{
private:
int data;
Node* next;
//...
public:
//...
}
class List
{
private:
Node* head;
//...
public:
//...
}
This one does not work because I can not change pointer and data in Node with functions in public area of class List. If I put data and next in public area of class Node, I am afraid that users can also directly change pointers and destroy the list.
What do people usually do when implementing a List? Thanks ahead for your advice:-)
std::list<>, and often not even that, opting for eitherstd::vector<>orstd::deque<>. That said, unless you have to expose the node as an external entity or are sharing it with other classes as their "node" type, there is little reason to make it stand-alone.