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