You need a doubly-linked list. This list uses a node class, in this case you can call it train
. Each node has a name
, as well as next
and previous
node. The list class will store the nodes.
The example below is a simple version where all the members are public
. You can improve it by declaring next
, prev
, head
, tail
as private
, then provide public
methods to access them.
The list should also cleanup after itself. In add
method there is a call to train *node = new train(s)
. This memory should be freed in destructor using delete
. You have to walk the list and delete the memory for each node.
See also these references:
https://en.wikipedia.org/wiki/Doubly_linked_list
http://www.dailyfreecode.com/Code/double-linked-list-cpp-3422.aspx
class train
{
public:
string name;
train *next, *prev;
train(const string &s) {name = s; next = prev = nullptr;}
};
class linked_list
{
public:
train *head, *tail;
linked_list() { head = tail = nullptr; }
linked_list() { /*add cleanup routine*/ }
train* add(const string &s)
{
train *node = new train(s);
if(!head) {
head = tail = node;
}
else {
node->prev = tail;
tail->next = node;
tail = node;
}
return node;
}
};
int main()
{
linked_list list;
train *walk, *node = nullptr;
string name;
while(true) {
char choice="a";
if(node) {
cout << "(A)dd, (L)ist, (N)ext, (P)revious, (Q)uit ?\n";
cin >> choice;
choice = tolower(choice);
}
switch(choice) {
case 'a':
cout << "enter name:\n";
cin >> name;
node = list.add(name);
break;
case 'l':
cout << "list:\n";
walk = list.head;
while(walk) {
cout << walk->name << "\n";
walk = walk->next;
}
break;
case 'n':
if(node->next) {
node = node->next;
cout << "next: " << node->name << "\n";
}
break;
case 'p':
if(node->prev) {
node = node->prev;
cout << "previous: " << node->name << "\n";
}
break;
default: break;
}
if(choice == 'q')
break;
}
return 0;
}
1
solved Pointers/Class C++