-3

My book is asking me to make a recursive definition of a singly linked list. I have no idea at all how to do that. Can someone please help me out with a sample? Thanks

  • I don't know how much more detailed I can get in my question. What I asked in my questions is SPECIFICALLY what I want to know. I don't know why you guys have to be so damned specific on a question. This forum is to ask questions but it seems like there's ALWAY a problem with my question when I ask it. – Elliot Werner Nov 06 '16 at 03:28

1 Answers1

0

It's just like a normal linked list except the iteration is performed by recursion rather than loops.

First, a little light reading: What is recursion and when should I use it?

For example, a loop-based function to find the last node could be:

Node * getLast(Node * current)
{
    while (current->next == null)
    { // loop until no more nodes
        current = current.next;
    }
    return current; // return last node
}

While the recursive version only checks if the current node is the last and calls itself with the next node if there is a next node.

Node * getLast(Node * current)
{
    if (current->next == null)
    { // found last node. return it
        return current;
    }
    else
    { // see if next node is last node
        return getLast(current->next);
    }
}
Community
  • 1
  • 1
user4581301
  • 33,082
  • 7
  • 33
  • 54