------------------------------------------------------------------------------
MC logo
Linked List Node Classes
[^] Code Examples
------------------------------------------------------------------------------
<<Shape Driver IV linkednode.h Linked List Classes>>
#ifndef _NODE_
#define _NODE_

#include <iostream>

using namespace std;

/*
 * This contains the objects which describe nodes for single and double linked
 * list objects.  (List objects defined in list.h.)
 */

// Node with one next for a single-linked list.
class OneWayNode
{
    protected:
        int cont;                       // Denotes contents of node.
        OneWayNode *next;               // Next node in linked list.

    private:
        friend class OneWayList;        // User of the private calls.

        // This is used to destroy the list.  Just call it on the head
        // node, if any.
        void Die()
        {
                if(next != NULL)
                        next->Die();
                delete this;
        }

        // This is used to print the list members.
        void Print(ostream &st)
        {
                st << cont;
                if(next != NULL)
                {
                        st << ',';
                        next->Print(st);
                }
        }

    public:
        // Construct, with given contents.
        OneWayNode(int i, OneWayNode *n = NULL)
        {
                cont = i;
                next = n;
        }

        // Manipulate contents.
        int Cont() const { return cont; }
        void Cont(int i) { cont = i; }

        // Manipulate the link.
        OneWayNode* Next() const { return next; }
        void Next(OneWayNode *n) { next = n; }
};

// Node with two links for a double-linked list.
class TwoWayNode: public OneWayNode
{
    protected:
        TwoWayNode *prev;                       // Point to previous node.
    public:
        // Build me one with the specified contents.
        TwoWayNode(int i, TwoWayNode *pv = NULL, TwoWayNode *nx = NULL):
                                OneWayNode(i, nx)
        {
                prev = pv;
        }

        // Also, manipulate the previous pointer.
        TwoWayNode* Prev() const { return prev; }
        void Prev(TwoWayNode *n) { prev = n; }
};

#endif

The friend declaration allows other classes access to the declarer's private data.
<<Shape Driver IV Linked List Classes>>