hello everyone,
I'm writing a function traverse for a doubly liked list, I can only use these private members: Node *current , int count, int mutable current_position
and one one private member function void set_position(int position) const

The post condition of member function traverse is the action specified by function *visit has been performed on every entry of the list, begining at position 0 and doing each in turn

void List::traverse(void (*visit)(List_entry &))
{
     set_position(0);
     while(current!=NULL)
{  
    (*visit)(current->entry);
     current=current->next;
}
}

i tried to reset the position from the current position to 0 then read the next items in the list :rolleyes: , the instructor told me there are two mistakes in this..i really can't figure them out :eek: can anyone please help me?

>the instructor told me there are two mistakes in this
Design or implementation? Design-wise, the use of integers as position markers is silly, pointers to nodes would make more sense. It also suggests that the list is always in a certain "state" where to get to the front of the list (for example), you have to change the state until you get where you want. This goes against a more flexible design where you can just say:

List::iterator i = mylist.head();
while ( i != mylist.end() ) {
  visit ( it->entry );
  ++i;
}

Implementation-wise, you don't change current_position or reset to current_position. That suggests an error because the current position will be marked incorrectly after traversal. Without the rest of your code for context, I would say that this makes more sense:

void List::traverse(void (*visit)(List_entry &))
{
  int save = current_position;

  set_position ( 0 );

  while ( current != NULL ) {
    visit ( current->entry ); // Dereference not needed
    current = current->next;
  }

  set_position ( save );
}

This assumes that set_position resets current and current_position accordingly.

>i really can't figure them out
When in doubt, ask your teacher. If he refuses to tell you then either he thinks the problems are easily discovered, or he's hindering you unnecessarily. It would wager the latter in this case.

Thanx Narue, it makes more sense now it's an implementation problem the mess was caused from the current pointer i fixed the code
thank you

This article has been dead for over six months. Start a new discussion instead.