I tried to modify the code a few times but was unable to find the mistake in the code. My program is running but I have a hard time adding the node to the correct position.
#include<iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
}*HEAD=NULL;
void create(int a[],int n)
{
struct Node *p;
cout<<"Enter the number of elements of LL you want to display "<<endl;
cin>>n;
for(int i=0;i<n;i++)
{
if(i==0)
{
HEAD=new Node;
p=HEAD;
p->data=a[0];
}
else
{
p->next=new Node;
p=p->next;
p->data=a[i];
}
p->next=NULL;
}
}
void insertion(struct Node *p,int pos,int x)
{
struct Node *t;
int i,n;
if(pos<0||pos>n)
cout<<"Invalid position "<<endl;
t=new Node;
t->data=x;
// t->next==NULL;
if(pos==0)
{
t->next=HEAD;
HEAD=t;
}
else
for(i=0;i<pos-1;i++)
{
p=p->next;
t->next=p->next;
p->next=t;
}
}
void display(struct Node *HEAD)
{
struct Node *p;
p=HEAD;
while(p!=NULL)
{
cout<<p->data;
p=p->next;
}
}
int main()
{
struct Node *temp;
int n;
cout<<"enter the value of n "<<endl;
cin>>n;
int a[n];
cout<<"Array elements are "<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
create(a,n);
insertion(HEAD,1,15);
display(HEAD);
}