r/learnprogramming • u/FantasticFourSkin • Jan 31 '14
Can someone ELI5 linked lists?
Part of my assignment for my online class involves linked lists and we don't really go over them. I looked around online and I'm slightly confused by all the explainations since I'm fairly new to programming. Can someone dumb it down for me?
77
Upvotes
View all comments
Show parent comment
5
u/DestroyerOfWombs Jan 31 '14 edited Feb 01 '14
That is a benefit of a linked list, but not the important benefit. A dynamic array is much quicker for element access if you simply want a variable size container. The benefit of a linked list is that unlike a dynamic array, you can insert data anywhere in the structure without having to move all the data that come after by one position.
If you have 50 elements in your dynamic array and you want to insert a new element at position 4, you have to do 45 operations to move 45 elements over one spot each. With a linked list, you can simply change the pointer in element 3 to point to the new entry and have the new entry point to old element 4 and you're good in 2 operations.
If you simply want a variable size data structure and you know that you don't need to insert in the middle, a dynamic array would perform better than a linked list. This is because in an array you can instantly access any element. Instead of following the links from node to node like in a linked list, you can take the (memory address of the first element) + (size of the data type * index of the the element you want to access) and you're at the element.