void every_nth( istream & instr, int n ) { list<float> values; float in_val; while ( instr >> in_val ) values.push_back(in_val); list<float>::reverse_iterator p = values.rbegin(); int i=0; for ( ; p != values.rend(); ++p, ++i ) if ( i%n == 0 ) cout << *p << endl; }Note that you might have used two nested loops for the printing operation. That is likely to be an equally valid solution. Also, you could have called the reverse function and then just used an ordinary iterator.
The solution for vector is exactly the same, with the word list replaced by the word vector!
p
points to the head of the
reversed part of the list and q
points to the head of the
unreversed part and *p
is the former predecessor of *q
.
void Reverse( Node* & head ) { if ( !head ) return; Node * p = head; Node * q = head->next; while (q) { Node * r = q->next; q->next = p; // reverse the direction of node *q p = q; q = r; } head = p; }
Here is the solution for doubly-linked list. Note that fewer scratch pointers are needed because each node knows both its predecessor and successor.
void Reverse( Node* & head ) { if ( !head ) return; do { Node * old_next = head->next; head->next = head->prev; head->prev = old_next; if ( !old_next ) break; // end of list has been reached head = old_next; } while (true); }