<<< The Node class constructor     Index     Removing a node from the list >>>

7. Inserting a node into a singly-linked list

  • 
    // Node.h
    class Node {
        Node* pnext;
    public:
        int data;
    
        // Insert new node in front:
        void insert( Node* newNode )
        {
            newNode->pnext = pnext;
            pnext = newNode;
        }
    };
    
    

    The following diagram shows how it works:

      Singly-linked list insert-after

  • To insert a new node into the list, program must keep track of the previous node.

  • Inserting a node before an existing one cannot be done.

    
    #include "Node.h"
    int main ( )
    {
        Node A;
        Node B;
        Node C;
    
        A.data = 12;
        B.data = 99;
        C.data = 37;
    
        A.insert( &C );
        A.insert( &B );
    
        return 0;
    }
    
    

      Singly-linked list

<<< The Node class constructor     Index     Removing a node from the list >>>