<<< Removing a node from the list     Index     Print contents of the list >>>

9. List size and distance between the nodes

  • List traversal employs a linear search algorithm:

    
    // Node.h
    class Node {
        Node* pnext;
    public:
        int data;
        // Measure distance to other node:
        int distance( Node const* other ) const
        {
            int hops = 1;
            Node const* iter = pnext;
            while ( iter != other ) {
                if ( iter == NULL )
                    return hops - 1;
                iter = iter->pnext;
                ++hops;
            }
            return hops;
        }
        // Calculate number of nodes in the list:
        size_t size() const
        {
            return distance( NULL );
        }
    };
    
    
  • 
    #include <iostream>
    #include "Node.h"
    using namespace std;
    int main ( )
    {
        Node A;
        Node B;
        Node C;
        A.data = 12;
        B.data = 99;
        C.data = 37;
        A.insert( &C );
        A.insert( &B );
        cout << "List size is: " << A.size();
        return 0;
    }
    
    

      Singly-linked list

  • The list is searched until the node in question is found.

  • The distance is measured by the number of hops required.

<<< Removing a node from the list     Index     Print contents of the list >>>