i dont why it isnt printing the linked list

this is my code for inserting a node at the head of the linked list. there is no error but my printllist function is not working I don’t know why. I think I have done silly somewhere. help me out I am stuck here for 3 hours.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;
  class Node
   {   public:
       int data;
       Node* next;
   };



void insert(int y,Node* head){
  
   Node *temp=new Node();
   temp->data=y;
   temp->next=head;
   head=temp;

}

void printllist(Node *head){

   if(head=NULL)
   {
      cout<<"list is empty"<<endl;
   }
   else
   {
      while(head!=NULL)
      {
         cout<<head->data<<" ";
         head=head->next;
      }
   }

}

int main(){

   Node *head;
   head=NULL;
   int x,y,z;

   cout<<"hey can you tell me how many number you want to insert"<<endl;
   cin>>x;
   for(int i=0;i<x;i++)
   {
      cout<<"enter the data that you want to insert"<<endl;
      cin>>y;
      insert(y,head);
      printllist(head);
   }

   return 0;
}

Answer

You need to pass the head of the linked list by reference so that the changes which are made in the insert function actually remain preserved between the function calls. Also, keep in mind that all the new nodes are inserted at the beginning of the linked list. So, for example if you enter 1,2,3 as the three elements of the linked list, the print function will print 3 2 1.

Try this:

#include <iostream>
#include <bits/stdc++.h>

using namespace std;
  class Node
   {   public:
       int data;
        Node* next;
   };
void insert(int y,Node** head){
  
Node* temp = new Node();
    temp->data = y; 
    temp->next = *head; 
    *head = temp;
}
void printllist(Node* head)
{
    if(head==NULL)
        cout<<"List is empty";
    while(head!=NULL)
    {
       cout<<head->data<<" ";
       head=head->next;
    }
}

int main(){

Node *head;
head=NULL;
int x,y,z;
  cout<<"hey can you tell me how many number you want to insert"<<endl;
  cin>>x;
  for(int i=0;i<x;i++)
  {   cout<<"enter the data that you want to insert"<<endl;
 cin>>y;
 insert(y,&head);
}
printllist(head);

return 0;
}