I am implementing my own linkedlist in C++ as part of a class assignment. My main concern isn't with the style of the code nor the pros/cons of including or not including certain features as I am still developing member functions.
I would mainly like to know if my approach of declaring LinkedList
as a friend
of Node
is reasonable. My decision for doing this comes from the fact that there is absolutely no need for anything to access my Node
class besides LinkedList
(e.g. I don't want to be able to create a Node
object in main). When I do this, however, I find myself no longer needing public
and private
access modifiers for Node
. Furthermore, I don't particularly need getter/setter methods as I can just access Node
's member variables directly from LinkedList
(you can see below that I don't call Node::getVal()
or Node::getNext()
once).
Coming from the world of Java, it seems really strange to ever access an object's internal data directly without getters/setters. What do you guys think? Does this friend
relation make sense?
template <typename T> class Node
{
friend class LinkedList<T>;
// private:
Node<T>* next; // CAN ACCESS MEMBERS DIRECTLY BECAUSE OF FRIEND DECLARATION
T value;
// public:
Node<T>(T valuep)
{
value = valuep;
next = NULL;
}
void insert(T valuep)
{
if(next == NULL)
{
next = new Node<T>(valuep);
return;
}
else
{
next->insert(valuep);
}
}
T getVal() // DON'T NEED BECAUSE OF FRIEND DECLARATION
{
return value;
}
Node<T>* getNext() // DON'T NEED BECAUSE OF FRIEND DECLARATION
{
return next;
}
};
template <typename T> class LinkedList
{
private:
Node<T>* head;
public:
LinkedList<T>()
{
head = NULL;
}
~LinkedList<T>()
{
Node<T>* currentNode = head;
while(currentNode!=NULL)
{
Node<T>* next = currentNode->next;
delete currentNode;
currentNode = next;
}
}
void insert(T valuep)
{
if (head == NULL)
{
head = new Node<T>(valuep);
return;
}
else
{
head->insert(valuep);
}
}
void print()
{
Node<T>* temp = head;
while(temp!=NULL)
{
std::cout << temp->value << std::endl; // ACCESS Node's MEMBERS DIRECTLY
temp = temp->next; // ACCESS Node's MEMBERS DIRECTLY
}
}
void update(int indexp, T valuep)
{
if(indexp==0)
{
head->value = valuep; // ACCESS Node's MEMBERS DIRECTLY
}
}
};