Home > Blockchain >  How to use function members of a class recursively?
How to use function members of a class recursively?

Time:03-21

How can you define a function of a class to be recursive?, this is what I have been doing:

class A
{
 private:
  
 public:
  _recursive(A *var);
  recursive()
}

A::recursive()
{
  _recursive(this)
}

A::_recursive(A *var)
{
  _recursive(var->next);
}

And on main:

A *temp = new A();
A->recursive();

I have also tried (same class as before)

A *temp = new A();
A->_recursive(&A);

There seems like this should be something somebody else has found and easier or more elegant way of doing so, I tried making the class simple just to demonstrate, but this is a single linked list transverse program so it needs recursion.

CodePudding user response:

Front-ending a recursive algorithm that, by its normative nature uses a parameterized gating is what I think you're actually trying to ask about. For a linked list, for example, given this procedural typical recursive solution where the descent is parameterized and the base-case is exit-on-null:

struct Node
{
    int data;
    Node *next;
};

void print_list(Node *p)
{
    if (!p)
        return;

    std::cout << p->data << ' ';
    print_list(p->next);
}

You can do the same thing with a member function by throwing that base logic in as a condition of the recursion. For example:

struct Node
{
    Node *next;
    int data;
    
    void print()
    {
        std::cout << data << ' ';
        if (next)
        {
            next->print();
        }
    }
};

The same modus-operandi can be extended to more complex structures like a BST node:

struct BSTNode
{
    BSTNode *left;
    BSTNode *right;
    int data;
    
    void inorder()
    {
        if (left)
            left->inorder();

        std::cout << data << ' ';

        if (right)
            right->inorder();
    }
};

At least I think that's what you're asking about.

CodePudding user response:

this is a single linked list transverse program so it needs recursion.

You don't actually need a recursive loop at all. An iterative loop will suffice, and be safer for long lists as you won't run the risk of a stack overflow pushing each recursive call into the call stack (if you write the loop to use tail-call recursion, any decent compiler should be able to apply tail-call optimization to convert the recursive loop into an iterative loop), eg:

class A
{
 public:
  A *next;
  void doSomething();
}

A::doSomething()
{
  A* var = this;
  do {
    // do something with var...
    var = var->next;
  }
  while (var);
}
  • Related