------------------------------------------------------------------------------
MC logo
Linked List Implementation
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[Bounded Safe Array] [Bounded Safe Array Driver] [PrintMe Class] [PrintMe2 Class] [PrintMeLots Class] [PrintMeLots2 Class] [PrintMe Test Driver] [Linked List Node Classes] [Linked List Classes] [Linked List Implementation] [Linked List Driver] [Expression Calculator]
linkedlist.cc
#include "linkedlist.h"

/*
 * Bodies for the linked list and iterator classes.
 */

// Add the new item nd to a linked list, following curr.
void OneWayList::Add(OneWayNode *curr, OneWayNode *nd)
{
        // See if we are at "before," or in the list somewhere.
        if(curr == NULL)
        {
                // We are "before."  Add to the head of the list.
                nd->Next(head);
                head = nd;
        }
        else
        {
                // We are at a list member.  Add after it.
                nd->Next(curr->Next());
                curr->Next(nd);
        }
}

// Add to the double-linked.  Uses the single add, and does the extra work.
void TwoWayList::Add(TwoWayNode *curr, TwoWayNode *newnode)
{
        OneWayList::Add(curr, newnode);
        newnode->Prev((TwoWayNode*)curr);
        if(newnode->Next() != NULL)
                ((TwoWayNode *)newnode->Next())->Prev(newnode);
}

// Extract the value at the current location, or return 0 if at "before."
int OneWayIter::Val()
{
        if(curr == NULL)
                return 0;
        else
                return curr->Cont();
}

// Advance to the next position.  If already at the end, don't change.
OneWayIter& OneWayIter::operator++()
{
        if(curr == NULL)                        // Are we at "before"?
                curr = list.head;               // Yep.  To first, if any.
        else                                    // We are at some member.
                if(curr->Next() != NULL)        // Is there a next one?
                        curr = curr->Next();    // Then go there.
        return *this;                           // Okay....
}

// Print the list.  This uses the method OneWayNode::Print(), which runs
// through the list of objects, each one printing its contents.
void OneWayList::Print(ostream &o /* = cout */) const
{
        o << "(";
        if(head != NULL)
                head->Print(o);         // Needs friend of OneWayNode.
        o << ")";
}

// Move back one.
TwoWayIter& TwoWayIter::operator--()
{
        if(curr != NULL)
                curr = ((TwoWayNode*)curr)->Prev();
        return *this;
}