caleb15 caleb15 - 29 days ago 9
C++ Question

Creating a recursive function to add a node to a linked list

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

I am suspicious about two things in your code.

  1. 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).

  2. 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.

Comments