The requirements seem to me to be in addition to
void insertHead(Node*& head, Node*& entry);
you will need a
void insertHead(Node*& head, const Node::nodeDatatype & data);
the reference to avoid a copy of data
(kind of pointless with an int
, but the typedef
could be changed to something beefier) and const
because insertHead
has no business modifying the data. The const also allows the function to accept a wider variety of variable types.
This insertHead
overload would have to construct a Node
to hold the data, and after that the Node
accepting insertHead
can be called. Eg:
void insertHead(Node*& head, const Node::nodeDatatype & data)
{
Node * newNode = new Node(data);
insertHead(head, newNode);
}
This is all predicated on
void insertHead(Node*& head, Node*& entry);
being implemented correctly and currently it is not. Let's fix that since the fix is really simple.
Node* insertHead(Node *head, Node *entry){
does not match the declaration. Use
void insertHead(Node*& head, Node*& entry){
instead. The rest of the function mostly does what you want, but does it in a very roundabout fashion.
Node* newNode = entry;
is not required. it doesn't do any harm, but let's gut it anyway and use entry all the way through.
newNode->setData = setData;
what is setData
? What's wrong with the data already in the node?
newNode-> next = NULL;
if(head == NULL){
head = entry;
}
else{
newNode->next = head;
head = newNode;
}
No need for most of the above. The new node goes in ahead of head
, so there's no need to test whether head
's null or not, just point the new node's next
at the same thing as head
. In other words, always do the else case.
return head;
This used to make sense, but now after the matching the definition and the declaration. Don't return a value from a void
function.
}
We wind up with
void insertHead(Node*& head, Node*& entry){
entry->next = head;
head = entry;
}
Bundling all this up we get,
class Node {
public:
typedef int nodeDatatype;
Node(
const nodeDatatype& initData = nodeDatatype(),
Node* initLink = NULL)
{data = initData; link = initLink;}
void setData(const nodeDatatype& new_data) {data = new_data;}
void setLink(Node* new_link) {link = new_link;}
nodeDatatype getData() const {return data;}
const Node* getLink() const {return link;}
Node* getLink() {return link;}
private:
nodeDatatype data;
Node* link;
};
void insertHead(Node*& head, Node*& entry);
void insertHead(Node*& head, const Node::nodeDatatype & data);
And then the implementations
void insertHead(Node*& head, Node*& entry){
entry->link = head; // this line is currently impossible due to link being private
// perhaps these functions should be reworked into members
head = entry;
}
void insertHead(Node*& head, const Node::nodeDatatype & data)
{
Node * newNode = new Node(data);
insertHead(head, newNode);
}
Sidenote: Instead of typedef int nodeDatatype;
, consider making the class a template.