Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a [copy array to linked list] function?

What this supposed to do is:

  • Create an array with 4 elements.

  • Print these 4 elements.

  • Copy array elements to a created linked list in copy fucntion.

  • Print linked list with print and traverse fuction.

I tried this and it compiles, but crashes after printing the array.

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define ELEMENTS  4

struct node {
    int data;
    struct node *next;
};
struct node *head;

void insert(int x) {
    struct node *temp = malloc(sizeof(struct node));
    temp->data = x;
    temp->next = NULL;

    if (head != NULL)
        temp->next = head;
    head = temp;
}

void copy(struct node *head, int array[ELEMENTS], int n) {                       
    //copying array elements and create linked list

    struct node *temp = malloc(sizeof(struct node));
    temp->data = array[0];
    temp->next = NULL;
    head = temp;

    int i;
    for (i = 1; i < n; i++) {
        struct node *temp2 = malloc(sizeof(struct node));
        temp->next = temp2;
        temp2->data = array[i];
        temp2->next = NULL;
        temp = temp2;
    }
}

void printlist() {
    struct node*temp = head;
    printf("List is : ");

    while (temp->next != NULL) {
      printf(" %d ", temp->data);
      temp = temp->next;
    }
    printf("\n");
}

int main() {
    int *array = (int*)calloc(ELEMENTS , sizeof(int));
    int i = 0;
    for (i = 0; i < ELEMENTS; i++) {
        printf("arrays = [%d] ", i);
        scanf("%d", &array[i]);
    }

    for (i = 0; i < ELEMENTS; i++)
        printf("array [%d] = %d \n", i, array[i]);

        copy(head, array[ELEMENTS], ELEMENTS);
        printlist();

        getchar();
        return(0);
}

How to fix it?

like image 739
topcat Avatar asked Dec 11 '25 05:12

topcat


1 Answers

You dont need to pass head to the copy function because it is global and when you do you create a local pointer named head which gets destroyed as soon as function is over.

So copy should look like this

void copy(int array[ELEMENTS],int n)                         //copying array elements and create linked list
{
    struct node*temp = malloc(sizeof(struct node));
    temp->data=array[0];
    temp->next=NULL;
    head =temp;
    int i;
    for(i=1;i<n;i++)
    {
        struct node*temp2= malloc(sizeof(struct node));
        temp->next= temp2;
        temp2->data = array[i];
        temp2->next = NULL;
        temp=temp2;
     }  
}

Also while printing change while to

while(temp!=NULL)
    {
      printf(" %d ",temp->data);
      temp=temp->next;

    }
like image 166
Sniper Avatar answered Dec 12 '25 21:12

Sniper