caleb15 - 1 year ago 72

C++ Question

I am pretty new to pointers, one of my practice problems is to add a node to a linked-list recursively. This code works but I am wondering if this is the correct way to go about this problem.

`void addNode(node* head){`

if (head->next != NULL)

addNode(head->next);

if (head->next == NULL) {

node* newNode = new node;

newNode->next = NULL;

head->next = newNode;

}

}

Answer Source

I am suspicious about two things in your code.

What the data type

`node`

is and whether it includes some data fields that you need to somehow initialize. Currently a default constructor will be called, so all nodes in the linked list, added using your function, will be the same. That may or may not be OK. (Depending on what your prof had in mind. This is a homework question after all).Another issue that is not quite clear, is that you assume the linked list is always non-empty. If head is null your function will not work. I doubt that this is OK.