#include <iostream> #include <casa/Containers/Link.h> main() { Link<int> *hed = new Link<int>(23); hed = new Link<int>(12,0,hed); hed = new Link<int>(19,0,hed); hed = new Link<int>(10,0,hed); while (hed) { Link<int> *cur = hed; hed = hed->unlink(); cout << cur->val() << " "; delete cur; } cout << endl; }The output from the previous example would be:
10 19 12 23As each new link is being created, the new element goes at the beginning of the list because the previous head of the list, hed, is being passed in as the next list element.
This next example demonstrates how a queue could be created instead of a stack:
#include <iostream> #include <casa/Containers/Link.h> main() { Link<int> *hed = new Link<int>(23); Link<int> *cur = hed; cur = new Link<int>(12,cur); cur = new Link<int>(19,cur); cur = new Link<int>(10,cur); while (hed) { cur = hed; hed = hed->unlink(); cout << cur->val() << " "; delete cur; } cout << endl; }The output here would be:
23 12 19 10
These member functions allow traversal of the list. the next() functions retrieve the next element in the list, and prev() retrieves the previous element.
The non-const versions of these functions return a reference to the pointer to the next element in the list. This allows for modification of the list if necessary, e.g. for removal of elements.
This is where the maintenance of the list happens. The parameters are:
This destructor destroys the rest of the list, i.e. this object and all that follow.
If the destructor is called for a Link<t> in the middle of a list the elements which occur before the object will be left dangling, and the objects which follow the deleted object will also be deleted.
This function unlinks a given element of the list. It requires no parameters because the node has links to the previous and next elements in the list. This is useful when removing a single element from the list because the destructor, Link::~Link, will delete the rest of the list elements if they are linked in with this. This function returns the next element in the list.
The Link<t>* parameter is unused. It is a historical artifact which will be removed.