I am new to the idea of recursion in functions. For example, I'm building a program, but I want to try changing one of the functions to use recursion (so I can learn how it really works). Below is one of my functions, which I thought may be easiest to change to recursion.
I've tried to write it as recursion, but keep getting weird results when I do.
*note:
length, views, likes, title and such things are initialized in the .h file
void songs::SongsAddNewSong(char *newTitle, double newLength, int newViews, int newLikes)
{
songs *current = head;
songs *newNode = new songs();
if (current != nullptr)
{
current->next->songs::SongsAddNewSong(newTitle, newLength, newViews, newLikes);
}
if (current == nullptr) //if list is empty
{
//head = newNode; Is this needed? current is already equal to head
current = newNode;
strcpy(newNode->title, newTitle);
newNode->length = newLength;
newNode->views = newViews;
newNode->likes = newLikes;
current->next = nullptr;
}
}
The else statements messes around with current->next and newNode->next which will never happen in what I sent. Not all functions can/should be turned recursive. I'm not sure that this function is a good candidate to turn recursive. Without knowing the entire context of your code, can't know for certain. What I sent should work if the implementations you did are what I think they are.
I'm wondering about the structure of your list, though. You should have a class for the SongList and a separate struct for the nodes. The way you have it, either head is a global variable (NOOOOOO!!!!) or perhaps a static member variable (or even worse a non-static member variable) in the node class.
An example of a better design is something like this: