1

I'm trying to add a new node to the beginning of the linked list .So the newly added node becomes the new head of the Linked List and the previous head of the linked list becomes the second node. Here is my code:

    #include <iostream>
    #include <iomanip>

    class Node
    {
        public :
        int data ;
        Node * next ;
    } ;

    void printNodes(Node * node) ;
    void pushFront(Node * headReference, int newNode) ;

    int main()
    {
         Node * head = NULL,
         * second = NULL,
         * third = NULL ;

         head = new Node() ;
         second = new Node() ;
         third = new Node() ;

         head -> data = 1 ;
         head -> next = second ;

         second -> data = 2 ;
         second -> next = third ;

         third -> data = 3 ;
         third -> next = NULL ;

         pushFront(head, 4) ;
         printNodes(head) ;

         return 0 ;
   }

   //Printing the linked list nodes.
   void printNodes(Node * node)
   {
        int counter = 0 ;

        while(node != NULL)
        {
             ++ counter ;
             std::cout << "Node " << std::setfill('0')
                       << std::setw(2)
                       << counter
                       << " --> "
                       << node -> data
                       << std::endl ;

             node = node -> next ;
        }

        std::cout << "Linked List finished" << std::endl ;
   }

   //Inserting a new node on the front of the list.
   void pushFront(Node * headReference, int newData)
   {
        Node * newNode = new Node() ;

        newNode -> data  = newData ;

        newNode -> next = headReference ;

        headReference = newNode ;
   }

The output I expected is :

Node 01 --> 4

Node 02 --> 1

Node 03 --> 2

Node 04 --> 3

Linked List finished

The result I got is :

Node 01 --> 1

Node 02 --> 2

Node 03 --> 3

Linked List finished

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Mohamad
  • 37
  • 9

1 Answers1

2

You have to pass the head node by reference. For example

   void pushFront( Node * &headReference, int newData )
   {
        headReference = new Node { newData, headReference };
   }

Otherwise the function deals with a copy of the head node. Changing the copy within the function does not influence on the value of the original head node.

Another way is a C approach when passing by reference means passing an object through a pointer. In this case the function can look like

   void pushFront( Node * *headReference, int newData )
   {
        *headReference = new Node { newData, *headReference };
   }

and can be called as

pushFront( &head, 4 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335