Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi all,

I have written a linked list template but was wondering how I could convert the list (after it is created) to an array and then back into a list?

I tried a simple piece of code but it is not correct.

C++
arr[i] = root->data;


I also googled it but not getting the one which i really want... :(

So please help....
Posted
Updated 31-Jul-18 1:42am

1 solution

A linked list is designed such that it does not occupy a contiguous section of memory like an array does. The only way to convert a LL to an array is to copy the data to a contiguous section of memory element by element, something like this pseudo-code:

LinkedList current = root;
datatype[] array = new array[linked_list_count];
int i = 0;

while (current->next != null)
{
    array[i] = current->data;
    current = current->next; 
    i++;   
}


Its a little more complicated if it truely is C (not C++), since you have to allocate the correct amount of memory and increase the pointer value by the size of the data type. You could also create an array of pointers and just fill the array with the location of each linkedlist->data type which is more like a shallow copy of the linked list.
 
Share this answer
 
Comments
nv3 7-Nov-13 17:09pm    
5.
Atul Khanduri 7-Nov-13 17:15pm    
It is more complicated in C (not C++), it means in C++, we have some special functions for that??
Ron Beyer 7-Nov-13 17:28pm    
No, just means that in C++ you can use other pointer operations but the process is the same and memory management is easier.
Atul Khanduri 7-Nov-13 18:04pm    
Okay sir thanks...
Sergey Alexandrovich Kryukov 7-Nov-13 17:39pm    
Sure, a 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900