Insert an element at very beginning position. case-1 when the list is empty. case-2 When the list is not empty.
#include<iostream>
using namespace std;
struct Node{
int data;
Node* next; //link == head =stored the address of the next node
};
Node* head; //pointer to Head node with empty list
void Insert(int y);
void print();
int main(){
head = nullptr; //empty list
int n,y;
cout<<"how many number do you want to enter?"<<endl;
cin>>n;
for (int i=0;i<n;i++){
cout<<"Enter the number "<<i+1<<endl;
cin>>y;
Insert(y);
print();
}
}
void Insert(int y){
Node* temp = new Node(); //create dynamic memory allocation
temp->data = y;
temp->next = head; // temp->next = null; when list is empty
head = temp;
}
void print(){
Node* temp = head;
cout<<"List is: "<<endl;
while(temp!= nullptr){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}