r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

Show parent comments

11

u/MrSloppyPants Apr 05 '22 edited Apr 05 '22

Linked lists are just a data collection that points to the next one in the list. It can also point to the previous one in the list if it is a "doubly" linked list.

Where linked lists are useful is the speed with which you can perform insertion of items into the list. With an array, an insertion at any place but the end is at worst an O(n) operation because all the elements of the array must shift to accommodate the new item. Whereas inserting into a linked list is just changing the pointers of the items you are inserting between. At best it's an O(1) operation, constant time regardless of the size of the list.

1

u/SwishArmyKnife Apr 05 '22

So, essentially, the perk is being able to place what you want, where you want, quickly? I guess I could see that make sense. Placing at the end only would be as easy as using an ArrayList, but trying to place in the middle of that structure when that relies on a contiguous order would probably be quite a hassle.

1

u/MrSloppyPants Apr 05 '22

Yes, that's correct. Prioritize a linked list when speed of insertion is important. If you have data that is unordered and being sorted or otherwise ordered then you will gain efficiency by using a LL over an Array.

1

u/SwishArmyKnife Apr 05 '22

Nice, thanks for helping this make sense to me!