Reputation: 67
The implementation of Linked List in Mark Weiss's data structure book confuses me a little.
The List class contains a Node struct inside as follows.
...
class List {
private:
struct Node {
...
};
...
public:
...
private:
int theSize;
Node *head;
Node *tail;
};
My question is that is having a Node struct inside the List class really necessary? I think as long as the List class contains pointer to the header and tail node is enough. What is the advantage of having a Node struct as a private member?
Thanks!
Upvotes: 0
Views: 1695
Reputation: 206667
My question is that is having a Node struct inside the List class really necessary?
It's not necessary but it is better.
List::Node
can be different from Set::Node
, which can be different from DList::Node
, which can be different from Map::Node
. Having a Node
class outside of List
that is useful only for implementing List
does not make sense. You'll have to create ListNode
, SetNode
, etc. to make them distinct types.
Having Node
as a nested class makes sure that the details of the class are specific to List
.
It does not pollute the global namespace with type names that are not useful outside the implementation of List
.
It allows Node
to be private
to List
. The details of Node
are not exposed to users of List
unless the implementation of List
chooses to. In most cases, it is not exposed.
Upvotes: 1
Reputation: 53709
The reason that the Node structure would be declared as a private declaration within the List class is to keep it private to the implementation. This will ensure that the specific details of the implementation do not leak into the public interface. This is an effective way to abstract the interface from the internal implementation details, leaving those details free to change without impacting users of the List classes public interface.
Upvotes: 6