-4

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;
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
full_pr0
  • 51
  • 1
  • 5
  • 5
    Why are you using `malloc` in C++? Your code looks entirely like C code. – Cory Kramer Oct 16 '18 at 11:50
  • 2
    First write a function that adds a single element to the list. Then iterate over the array and for each element call that function. – eerorika Oct 16 '18 at 11:51
  • @CoryKramer yes its same as C – full_pr0 Oct 16 '18 at 11:51
  • Prefer using keyword: new, instead of malloc – Nitin Pawar Oct 16 '18 at 11:53
  • 2
    "but its not working" is not a useful problem description. How does it not work? Does it compile? If not, wasn't there an error message? If it compiles, does it run? Does it behave differently than you expected? How did you expect it to behave? How did it behave? – eerorika Oct 16 '18 at 11:53
  • 1
    Think about how many nodes you're creating. It should be as many as there are elements in the input array. Also, assigning a value to a pointer parameter has as much effect outside the function as assigning to an `int` parameter. – molbdnilo Oct 16 '18 at 11:56
  • @user2079303 edited, I'm new to stack overflow. thanks for your feedback :) – full_pr0 Oct 16 '18 at 11:58
  • 1
    Questions you can ask yourself: How likely is it that `head` will be `NULL` after you've assigned the result from `malloc` to it? What will happen at `head->data = ar1[i];` if `head` *is* `NULL`? – molbdnilo Oct 16 '18 at 11:59
  • @full_pr0 you should read this: [mcve]. And you last edit didn't make the question any clearer. The code you show here does not output anything and it doesn't ask for input either. There may also be problems in the part of the code you didn't show. – Jabberwocky Oct 16 '18 at 12:08

2 Answers2

1

There are many issues.The whole logic of your create function is wrong:

void create(struct node *head, int ar1[], int i1)
{
  struct node *temp, *p, *q;
  int i;

  head = (struct node*)malloc(sizeof(struct node));  // Problem 1
  temp = (struct node*)malloc(sizeof(struct node));

  for (i = 0; i < i1; i++)
  {
    if (head == NULL)                                // Problem 2
    {
      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;                                // Problem 3
    }
  }
}


...
create(myhead, myarray, maysize);                    // Problem 4
...

Problem 1

You allocate memory too early, you should allocate it only whe you really need it.

Problem 2

Partly induced by Problem 1: head cannot be NULL here (assuming mallocdoesn't fail, but that's another story) because you've assigned it to a non NULL value just before.

Problem 3

Here p->next is always NULL because of the while loop just above.

Problem 4

Suppose you cann create likes this:

...
myhead = NULL;
...
create(myhead, myarray, maysize);

myhead will still be NULL after the call to create, you should read this SO article.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

Just understand the logic by using paper and pencil , then sequentially optimize the code .

struct node
{
    int val;
    struct node *next;
};
struct node *head=NULL, *last=NULL;

void insert( int value)
{
    struct node *tmp;
    tmp=(struct node *)malloc(sizeof(struct node));
    tmp->val=value;
    tmp->next=NULL;
    if( head == NULL )
    {
        head=tmp;
        last=tmp;
    }
    else
    {
        last->next=tmp;
        last=tmp;
    }
}

void printlist()
{
    struct node *tmp=head;
    printf("The list is:");
    while( tmp != NULL )
    {
        printf(" %d", tmp->val);
        tmp=tmp->next;
    }
    printf("\n");
}
void search( )
{
    printf("Which value to Search?");
    int n, k=0;
    scanf("%d",&n);
    struct node *tmp=head;
    while( tmp != NULL )
    {
        if( tmp->val == n )
            k=1;
        tmp=tmp->next;
    }
    if( k )
        printf("Yes\n");
    else
        printf("No\n");
}
void deletenode( )
{
    int n, posi;
    printf("Where to Delete?\n");
    printf("1\tFirst Position\n");
    printf("2\tLast Position\n");
    printf("3\tAny Desired Position\n");
    scanf("%d",&n);
    if( n == 1 )
    {
        struct node *tmp=head;
        tmp=tmp->next;
        head=tmp;
        printlist();
    }
    else if( n == 2 )
    {
        struct node *tmp=head ;
        while( 1 )
        {
            if( tmp->next->next == NULL )
            {
                tmp->next=NULL;
                break;
            }
            else
                tmp=tmp->next;
        }
        printlist();
    }
    else if( n == 3 )
    {
        int i=1;
        printf("Enter Position: ");
        scanf("%d",&posi);
        struct node *tmp=head;
        while( tmp->next != NULL && i <= posi )
        {
            if( i+1 == posi )
            {
                tmp->next=tmp->next->next;
                break;
            }
            else
            {
                i++;
                tmp=tmp->next;
            }
        }
        printlist();
    }
}

void ins()
{
    int n, v, posi;
    printf("Where to insert?\n");
    printf("1\tFirst Position\n");
    printf("2\tLast Position\n");
    printf("3\tAny Desired Position\n");
    scanf("%d",&n);
    if( n == 1 )
    {
        printf("Enter value: ");
        scanf("%d",&v);
        struct node *tmp;
        tmp=(struct node *)malloc( sizeof(struct node));
        tmp->val=v;
        tmp->next=head;
        head=tmp;
        printlist();
    }
    else if( n == 2 )
    {
        printf("Enter value: ");
        scanf("%d",&v);
        struct node *tmp;
        tmp=(struct node *)malloc(sizeof(struct node));
        tmp->val=v;
        tmp->next=NULL;
        last->next=tmp;
        last=tmp;
        printlist();
    }
    else if(n == 3 )
    {
        int i=1;
        printf("Enter position: ");
        scanf("%d",&posi);
        printf("\nEnter value: ");
        scanf("%d",&n);
        struct node *tmp1, *tmp=head, *tmp2;
        tmp1=(struct node *)malloc(sizeof(struct node));
        tmp1->val=n;
        tmp1->next=NULL;
        while( tmp->next != NULL && i <= posi)
        {
            if( i+1 == posi )
            {
                tmp2=tmp->next;
                tmp->next=tmp1;
                tmp1->next=tmp2;
            }
            i++;
            tmp=tmp->next;
        }
        printlist();
    }
}
int main()
{
    int n;
    printf("Enter value & Enter -1 to exit.\n");
    while( 1 )
    {
        scanf("%d",&n);
        if( n < 0 )
            break;
        insert(n);
    }
    printlist();
    printf("Enter choice:\n\n");
    printf("1\tInsert\n");
    printf("2\tDelete\n");
    printf("3\tSearch\n");
    printf("4\tExit\n");
    scanf("%d",&n);
    if( n == 1 )
        ins();
    else if( n == 2 )
        deletenode();
    else if( n == 3 )
        search();
    else if( n == 4 )
        return 0;
    return 0;
}