recursive linked list function

I posted them question last week but no one answered to help me.

I have this function to get an entry in a linked list but I have to make it recursive. I was wondering if anyone can help

1
2
3
4
5
6
7
8
9
10
11
12
 template<class ItemType>
ItemType LinkedList<ItemType>::GetEntry(int position) const throw(PreconditionViolatedException)
{
   const bool able_to_get = (position >= 1) && (position <= item_count_);
   if (able_to_get) {
     Node<ItemType>* node_ptr = GetNodeAt(position);
     return node_ptr->GetItem();
   }
   
   const string message = "GetEntry() called with an empty list or invalid position."; 
   throw(PreconditionViolatedException(message)); 
}
Why do you have to do the GetEntry recursive?

How would you make the LinkedList<ItemType>::GetNodeAt(int) recursive?
Our prof is having us do it. I just do not know how
Does it have to be explicitly the GetEntry?

How has the GetNodeAt been implemented?
Yes it has to be GetEntry
Here is the GetNodeAt
1
2
3
4
5
6
7
8
9
10
11
12
template<class ItemType>
Node<ItemType>* LinkedList<ItemType>::GetNodeAt(int position) const{
 
   assert( (position >= 1) && (position <= item_count_) );
   Node<ItemType>* cur_ptr = head_ptr_;
   for (int i = 1; i < position; i++) {
     assert(cur_ptr != nullptr);
     cur_ptr = cur_ptr->GetNext();
   }
      
   return cur_ptr;
}  
Basic recursion could be trivial:
1
2
3
4
5
6
7
T * foo( T * node, int steps ) {
  if ( steps <= 1 ) {
    return node;
  } else {
    return foo( node->next, steps - 1 );
  }
}

but wrapping it in member function with all the exceptional error checking ...
I am just trying to figure it out, would this work?
I know for the parameters you need the position, and I guess the Node, but would there be a third param?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template<class ItemType>
ItemType LinkedList<ItemType>::GetEntry(int position, Node* curPtr) const throw(PreconditionViolatedException)
{
     Node<ItemType>* node_ptr = GetNodeAt(position);
     if(curPtr != NULL){
            if(node_ptr==curPtr->GetItem()){
                    return node_ptr->GetItem();
            else
                   return GetEntry(position, curPtr->GetNext());                      
   }
    else{
                  const string message = "GetEntry() called with an empty list or invalid position."; 
   throw(PreconditionViolatedException(message)); 
         }
}

Below is the original function
1
2
3
4
5
6
7
8
9
10
11
12
template<class ItemType>
ItemType LinkedList<ItemType>::GetEntry(int position) const throw(PreconditionViolatedException)
{
   const bool able_to_get = (position >= 1) && (position <= item_count_);
   if (able_to_get) {
     Node<ItemType>* node_ptr = GetNodeAt(position);
     return node_ptr->GetItem();
   }
   
   const string message = "GetEntry() called with an empty list or invalid position."; 
   throw(PreconditionViolatedException(message)); 
}
Last edited on
Topic archived. No new replies allowed.