TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Neil Heller
from: Darin McBride
date: 2004-04-19 18:08:10
subject: Linked List

Hello Neil!

Replying to a message of Neil Heller to All:

 NH> Reverse a linked list in C++. You cannot make a new linked list. The 
 NH> functions below are the only ones at your disposal. Though you can
 NH> write  your own.

Actually, what I would suggest is to use a new class.  Or two, actually.  I
like the Standard Template Library's methodology, and use it in my own
code.

Separate your container (LL) from the way you iterate through the container
(iterator).

So, there's no "getFirst()" returning Node.  There's a
"first()" returning "iterator" (not iterator* nor
iterator&).  There's a "last()" that returns iterator
(actually referencing one past the last item in the list, although what
that really means can be defined by the iterator internally).  And the
iterator object can handle ++ and -- to go back and forth.

You can then also create a reverse_first() and reverse_last() which both
return reverse_iterator objects.  The meaning of ++ and -- are then
"reversed" in this iterator.

Then, when you have an iterator object, i, you use "*i" to get at
the object embedded inside.  If the object is a real object such that
you'll call methods on it, you should use "(*i)", e.g.,
"(*i).getValue()".  Using i->getValue() will not work because
i is an iterator object, not a pointer.  The iterator object can override
the operator* such that (*i) is a reference to the underlying Node object.

This gives way more flexibility to do what you want.  The list can then
exist simultaneously forwards and backwards.  You can iterate through the
list inside an iteration through the list:

for (iterator i = list.first(); i != list.last(); ++i)
{
  for (iterator j = list.first(); j != list.last(); ++j)
  {
    ...
  }
}

One of my coworkers thought this was stupid.  Until he hit a bug where code
did exactly this (there were three or four levels of function calls between
them).  His code broke.

My code, using iterators, never has this problem, since independant
iterators keep their own state independant of the container.

I do understand I didn't quite answer your question.  But I've never been
fond of boxes ;-)

Darin

---
* Origin: Tanktalus' Tower BBS (1:250/102)
SEEN-BY: 633/267 270
@PATH: 250/102 99 10/345 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.