TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Neil Heller
from: Jasen Betts
date: 2004-04-20 18:35:42
subject: Linked List

Hi Neil.

19-Apr-04 12:17:04, Neil Heller wrote 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 write
 NH> your own.

 NH>    class LL
 NH>    {
 NH>    public:
 NH>      Node* getFirst();                  // returns NULL if list is empty
 NH>      void add(Node* node);              // adds to end of list
 NH>      void remove(Node* node);
 NH>      Node* next(Node* curNode);         // returns next node after
 NH>                                         // curNode in the list
 NH>                                         // returns NULL if nothing is
 NH>                                         // next
 NH>    };

looks more like a logic problem than a programmming problem.
what a sparse interface!

add() the second-last node to the end of the list and then remove () the
the old second last node, repeat with the third-last node etc until you've
done the whole list.

It's easiest to do this recursively.


This looks suspiciously like a homeworks question :)



maybe something like this (untested)


static void recurse_reverse(LL ll,Node *me)
{
  if(me)
    {
      Node *you;
      recurse_reverse(ll,you=ll.next(me));
      if(you)
        {
          ll.add(me);
          ll.remove(me);
        }
    }
}

void reverselist(LL ll)
{
  recurse_reverse(ll, ll.getfirst());
}


 -=> Bye <=-

---
* Origin: One less than the checksum of "Jasen Betts" (3:640/1042)
SEEN-BY: 633/267 270
@PATH: 640/1042 531 954 774/605 123/500 106/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™.