I am new at linked List. Recently I have tried to create a program which takes an array and its size as input. then it converts the array into a linked list and print elements. But the program is not working and I guess it is because the head pointer get changed. So, what I can do to keep the head node unchanged?
#include<bits/stdc++.h>
using namespace std ;
struct node
{
int data ;
node* link ;
};
node* create_linkedlist (int ara[] , int siz )
{
node* head = NULL ;
node* temp = new node() ;
temp->data = ara[0] ;
temp->link = NULL ;
head = temp ;
node* tmhead = head->link ;
node* temp2 ;
for(int i = 1 ; i < siz ; i++)
{
temp2 = new node() ;
temp2->data = ara[i] ;
temp2->link = NULL ;
while ( tmhead->link!= NULL)
{
tmhead = tmhead->link ;
}
tmhead->link = temp2 ;
}
return head ;
}
void printlist( node* h_ref )
{
while (h_ref != NULL)
{
printf("%d " , h_ref->data) ;
h_ref = h_ref->link ;
}
}
int main()
{
int siz ;
cin>> siz ;
int ara[siz + 2];
for(int i = 0 ; i < siz ; i++)
{
cin >> ara[i] ;
}
node* hd = create_linkedlist(ara , siz) ;
node* temp = hd ;
printlist(temp) ;
return 0 ;
}