------------------------------------------------------------------------------
MC logo
Linked List (Classes)
[^] Code Examples
------------------------------------------------------------------------------
<<Linked List (Structs) ilink.cc Multi-File Programs>>
#include <iostream>

using namespace std;

/* Linked list node structure. */
class lnode
{
        int _cont;              // Contents.
        lnode *_next;           // Next node.
public:
        // Constructor.
        lnode(int c, struct lnode *n = 0) { _cont = c; _next = n; }

        // Print the node and its successors.
        void print(ostream &strm) {
                strm << _cont;
                if(_next) {
                        strm << " ";
                        _next->print(strm);
                } else
                        strm << endl;
        }

        // Delete this node and all successors.
        void kill() { if(_next) _next->kill(); delete this; }
};

main()
{
        // Linked list head.
        lnode *lhead = 0;

        // Read the list contents.  The list is formed in reverse order.
        int newval;
        while(cin >> newval)
        {
                lnode *newnode = new lnode(newval, lhead);
                lhead = newnode;
        }

        cout << "-------------------------------------------------" << endl;

        // If no nodes, bail.
        if(lhead == 0) exit(0);

        // Print the list.
        lhead->print(cout);

        // Free the list.
        lhead->kill();
}

This uses a class to implement the linked list. The nodes are created with a constructor that creates the object and fills in its values.
<<Linked List (Structs) Multi-File Programs>>