I'm using lists and arrays very often, I am wondering what is faster, array or list?
Let's say we have array of integers and linked-list, both hold same values.
int array_data[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
typedef struct node_data{
int data;
struct node_data * next;
} list_data;
____ ____ ____ ____ ____ ____ ____ ____ ____ ____
list_data *d = -> | 1| -> | 2| -> | 3| -> | 4| -> | 5| -> | 6| -> | 7| -> | 8| -> | 9| -> |10| -> NULL
If I want to get value of array_data on index 6, I'll use array_data[6]
and get value of 7. But what if I want same data from list? Should I go from start and count hops till I reach asked index get_data(d,6)
? Or there is better way to do this?
int get_data(list_data *l, int index){
int i = 0;
while(l != NULL){
if(index == i){
return l -> data;
}
i++;
l = l -> next;
}
return 0;
}
How about using array of pointers to list elements? Will be this best solution in case I have more then 100,000 records or even more to save, and each record contains more then one data type. I'll mostly need insertion to the end, and very frequently access to elements.
Thanks!
You are correct to consider the question each time; when deciding whether to implement an array, linked-list (or other) structure.
ARRAY
LINKED-LIST
There are other structures that even combine arrays with linked list, such as hash tables, binary trees, n-trees, random-access-list, etc., each comes with various characteristics to consider.