I have array elements ar1[i]
i want to add the data of this array into linked list
struct node
{
int data;
struct node*next;
};
void create(struct node *head,int ar1[] int i1)
{
struct node *temp, *p, *q;
int i;
head = (struct node*)malloc(sizeof(struct node));
temp = (struct node*)malloc(sizeof(struct node));
for (i=0; i<i1; i++) //lets say i1 is no. of data in array
{
if(head == NULL)
{
head->data = ar1[i];
head->next = NULL;
}
else
{
temp->data = ar1[i];
temp->next = NULL;
p = head;
while(p->next != NULL)
p = p->next;
p->next = temp;
}
}
I did this program but its not working. It is accepting input data but not showing output and neither terminating the program.
Edit : As everyone suggested in comments I tried my best and came up with solution. Actually my program was to get at most 10 digit number from user and perform Arithmetic operations on it.
Here is my code :
/*
WAP to store at most 10 digit integer in a Singly linked list and
perform
arithmetic operations on it.
*/
#include<iostream>
using namespace std;
struct node
{
int data;
struct node*next;
};
void create(struct node *head,int ar1[],int ar2[], int i1, int i2)
{
struct node *newNode, *temp;
int i=0;
head = (struct node *)malloc(sizeof(struct node));
if(head == NULL)
{
cout<<"Unable to allocate memory.";
}
else
{
head->data = ar1[i]; // Link the data field with data
head->next = NULL; // Link the address field to NULL
temp = head;
for(i=1; i<i1; i++) //Create n nodes and adds to linked list
{
newNode = (struct node *)malloc(sizeof(struct node));
if(newNode == NULL)
{
cout<<"Unable to allocate memory.";
break;
}
else
{
newNode->data = ar1[i];
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}
}
}
temp = head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp= temp->next;
}
}
int main()
{
struct node*head = NULL ;
int n1,n2;
int i1,i2,choice;
int ar1[10],ar2[10];
head = (struct node*)malloc(sizeof(struct node));
cout<<"Enter numbers you want to perform operations on\n1). ";
cin>>n1;
cout<<"2). ";
cin>>n2;
i1=0; i2=0;
while(n1) //getting each digit of given number
{
ar1[i1] = n1 %10;
n1 /= 10;
i1= i1 + 1;
}
while(n2) //getting each digit of given number
{
ar2[i2] = n2 % 10;
n2 /= 10;
i2++;
}
cout<<"\nChoose what operation you want to
perform:\n1.Addition\n2Subtraction\n";
cin>>choice;
create(head,ar1,ar2,i1,i2);
/*if(choice == 1) I comment out this part i.e. not important rn.
{
add(ar1,ar2);
}
else if (choice == 2)
sub();
else
{
cout<<"Please chose valid data\n";
}
*/
return 0;
}