// Prog: list.cpp
// definition and implementation of the class ifmp::list
#include
#include
namespace ifmp {
// default Constructor
template
list::list()
: head_(0)
{}
// destructor
template
list::~list()
{
clear();
}
// clear
template
void list::clear ()
{
node* p = head_;
while (p != 0) {
p = p->get_next();
delete head_;
head_ = p;
}
assert (head_ == 0);
}
// copy constructor
template
list::list (const list& l)
: head_ (0)
{
copy (l.head_);
}
// private copy method
template
void list::copy (const node* from)
{
assert (head_ == 0);
if (from != 0) {
// copy first element to head
head_ = new node (from->get_key());
const node* p = from->get_next();
node* q = head_;
// copy remaining elements
while (p != 0) {
q->set_next (new node (p->get_key()));
p = p->get_next();
q = q->get_next();
}
}
}
// assignment operator
template
list& list::operator= (const list& l)
{
if (head_ != l.head_) { // avoid self-assignment
clear();
copy (l.head_);
}
return *this;
}
// push_front
template
void list::push_front (T key)
{
head_ = new node (key, head_);
}
// push_back
template
void list::push_back (T key)
{
if (head_ == 0)
head_ = new node (key);
else {
node* p = head_;
while (p->get_next() != 0)
p = p->get_next();
p->set_next (new node (key));
}
}
// remove by key
template
void list::remove (T key)
{
node* previous = 0;
node* p = head_;
while (p != 0) {
if (p->get_key() == key) {
remove (previous, p);
return;
}
previous = p;
p = p->get_next();
}
}
// remove first element
template
void list::pop_front()
{
if (head_ != 0)
remove(0, head_);
}
// remove by pointer
template
void list::remove (node* previous, const node* p)
{
if (previous != 0)
previous->set_next(p->get_next());
else
head_ = p->get_next();
delete p;
}
template
const node* list::get_head() const
{
return head_;
}
// check if the list is empty
template
bool list::empty() const
{
return (head_ == 0);
}
}
// POST: *this is written to std::cout
template
std::ostream& operator<< (std::ostream& o, const ifmp::list& l) {
const ifmp::node* p = l.get_head();
while (p != 0) {
o << p->get_key() << " ";
p = (*p).get_next();
}
return o;
}