user974227
user974227

Reputation: 209

copy elements of an array to a linked list in C

i have an array, i want to create a doubly linked list from it,by transferring my elements to the nodes. and linking them through pointers(prev and next) what i did was

head = malloc(sizeof(struct)) head->prev=NULL head->next=NULL tail=head

for(i=0;i<num;i++){
    //copy data from arr[i] to tail
    temp=tail
    tail->next=malloc(sizeof(struct))
    tail=tail->next
    tail->prev=temp
}

now, how do i copy the data? temp, head and tail are pointers to structure

Upvotes: 0

Views: 8074

Answers (3)

onemach
onemach

Reputation: 4325

I guess you did not try writing and compiling. The elements of linked list should have at least some place to hold value from your array, let's say data of int type.

#include <stdio.h>
#include <malloc.h>
#define N 3

typedef struct a{
struct a* prev;
struct a* next;
int data;
}item;

int main(void)
{
item* head;
item* tail;
item* temp;
int num = N;
int data[N] = {1,2,3}; /*initialization*/
int i = 0;
head = (item*)malloc(sizeof(item));
head -> prev = NULL;
head -> next = NULL;
tail = head;
for(i = 0; i < num; i ++){
    temp = tail;
    tail -> next = (item*)malloc(sizeof(item));
    tail = tail -> next;
    tail -> next = NULL;
    tail -> data = data[i];
    tail -> prev = temp;
}
for(temp = head -> next; temp != NULL; temp = temp -> next) /*the following is for testing purpose*/
    printf("%d\t", temp -> data);
return 0;
}

Be aware that the head element does not contain what you want.

Upvotes: 3

Ashish
Ashish

Reputation: 1567

create temp node and parse linklist from to last node assign these detail

counter=start_node;
     temp=(struct NODE *)malloc(sizeof(struct NODE));   /*create new node*/
                temp->node_data=data;                               /*set data in new node*/
                while(counter -> next_node!=NULL)
                {
                    counter=counter->next_node;             /*increment in counter*/
                }

          temp->prev_node=counter;          /*set next node of new node*/
          counter->next_node = temp;
          temp->next_node = null;

here temp is the current node.

Upvotes: 1

MByD
MByD

Reputation: 137272

You need to save tail->prev, so you can do:

node * tailPrev = tail->prev;
memcpy(tail, &arr[i], sizeof(*tail));
tail->prev = tailPrev;
//continue with your code...

Upvotes: 0

Related Questions