Home > OS >  Template based Linked List - What should be Returned in search operation?
Template based Linked List - What should be Returned in search operation?

Time:01-04

I am working with Templates and defined the below templated ListNode.

template <typename T>
class ListNode{
    private :
    public:
        ListNode *left;
        ListNode *right;
        T data;
        ListNode(T data){ this->data = data; }
};

If I implement the search Operation on this Linked list with the below prototype what should be the return value of the function. If T is a pointer, I can return NULL, but if T is a Complete object, what should be the return type, and how can i differentiate if T is a pointer or a Complete object. How can this search function works for T where T can be a pointer Or a complete object.

T List_search(T srch_data);

    T List_search(T srch_data) {

        ListNode<T> *curr = head;
         while (curr) {
            if (comp_fn.compare_data (curr->data, srch_data) == 0)
                return curr->data;
            curr = curr->right;
        }
        return NULL;                   <<< Compilation error if T is complete object 
    }

CodePudding user response:

One option is to keep things simple: return the address of the found item, and nullptr if the item cannot be found:

   template <typename T>
   T* List_search(T srch_data) 
   {
        ListNode<T> *curr = head;
         while (curr) 
         {
            if (comp_fn.compare_data (curr->data, srch_data) == 0)
                return &curr->data;
            curr = curr->right;
         }
         return nullptr;
   }

The client would then check for a nullptr, and if it isn't a nullptr, can dereference the pointer.

For example, if the linked list node holds an int type:

int* foundData = List_search(10)
if ( foundData )
{
    std::cout << *foundData;
}
  •  Tags:  
  • Related