Suppose that we have a linked list template class named Link

Suppose that we have a linked list template class named LinkedList, and that we want to write a search member function which will return an integer: -1 if the value is not found, or 0, 1, 2, etc, indicating how far the element is from the head. So if the node at the head contains the value, you would return 0; if it was in the node after that you would return 1; etc. Assume the list is unsorted. The head of the list is stored in the member variable head, and the pointers are of type:

struct ListNode

{

T value;

ListNode *next;

// Constructor

ListNode( T value1, ListNode *next1 = NULL )

{

value = value1;

next = next1;

}

};

Write the code for the search() member function below. There is no need to write the prototype that would appear in the class declaration, just write the code for the function itself. Make sure you read the description of this function! Remember, the head of the list is stored in the member variable head.

template <class T>

int LinkedList<T>::search( T value )

{

}

Solution

LinkedList Template function search
The following function search that search for the value
in the linked list and returns the index of the node
and returns -1 if not found.
template <class T>
int LinkedList<T> :: search(const T&value)
{
   int pos=-1;
   int index=0;
   LinkedList nodePtr=head;
   bool found=false;
   while(nodPtr!=NULL && !found)
   {  
       if(nodePtr->value==value)
           {
           found=true;
           pos=index;
           }  
       index=index+1;      
   }
   return pos;
}

Suppose that we have a linked list template class named LinkedList, and that we want to write a search member function which will return an integer: -1 if the v
Suppose that we have a linked list template class named LinkedList, and that we want to write a search member function which will return an integer: -1 if the v

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site