Search code examples
c++shared-ptrsmart-pointers

Recursion in shared pointers while variable is defined in the class


I have a simple question. I have a LinkList class and root is initiated inside the class.

class LinkList {

     struct node {
        int data;
        shared_ptr<node> next;
    };

    shared_ptr<node> root;

    public:
       void insert(int data);
       void remove(int data);
       void print();
       int length();
       bool search_recursive(int data);
       bool search_recursiveUtil(shared_ptr<node> p, int data);
  }

Ideally I wanted to implement a recursive function to search for a node. Now I implemented in the following way:

bool LinkList::search_recursiveUtil(shared_ptr<node> p, int data){

     if(p == nullptr){
        return false;
     }

     if(p->data == data){
        return true;
     }

     return search_recursiveUtil(p->next, data);

}

bool LinkList::search_recursive(int data){

     shared_ptr<node> p = root;
     return search_recursiveUtil(p, data);
}

Now clearly you can see that since I do not want root to reach at the end of the linked list as other functions might use this head pointer to do something, I am taking a shared pointer P and traversing it. Now I want to have p to be pass to the "search_recursive" function but since it doesn't take shared_ptr argument so I had to take support of a "search_recursiveUtil" function.

My question is it is right way to approach? How can i implement this without having util function support?


Solution

  • Beside the consideration on why using a recursive search (the will soon result in a stack overflow as soon as the list becomes big enough) instead of a iterating one, since pointers are passed by value, there is no need of p: just call return search_recursiveUtil(root, data). Your reasoning abut root to reach the end of the list is a misconception.

    The use of an xUtil function taking a positional parameter not required when calling the search from outside can be a good idea, just make it private to the class, so that -from outside- your interface will be just the search_recursive function.

    Also, declare both the functions const, since they are not supposed to modify the data.

    An alternative can be place the "Util" function as a node member, so that you can do

    bool LinkList::node::search_recursiveUtil(int src_data){
    
         if(data == src_data)
            return true;
    
         if(pnext == nullptr)
            return false;
    
         return pnext->search_recursiveUtil(src_data);
    
    }
    

    called as

    bool LinkList::search_recursive(int data){
    
         root->search_recursiveUtil(data);
    }