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

7

u/SwishArmyKnife Apr 05 '22

Linked lists have been one thing I can’t grasp. One, I don’t think I understand why sequential traversal would be preferred over sequential access. Two, the code for navigating to each new one just doesn’t make sense to me. I feel like I end up looking at it like every 2 months and nothing new sticks or clicks.

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!

1

u/SquarePixel Apr 06 '22

Placing at the end can even become problematic sometimes if not enough memory was initially allocated to store the array too. With a linked list each node can be allocated as needed.

0

u/[deleted] Apr 05 '22

[deleted]

5

u/ShelZuuz Apr 06 '22 edited Apr 06 '22

And that's assuming your array even has space! What if your array is full and you want to add more stuff? Well, you can't just say "I want a bigger block", because this array is already built and there might be stuff next to it. So what happens is you make a new array somewhere, double the size, and then move everyone from your old array into your new array. As you can imagine, it's not the most efficient process.

So just want to point out, this is theoretical. On paper it's faster inserting into the middle of a linked list if you assume all memory accesses are the same.

However, it's not because of how memory prefetching works. If you start accessing elements in an array, the prefetcher will realize you're doing sequential access and fetch additional elements even before you ask for it. It can't do this with a linked list as there are pointers stored in there and the prefetcher has no idea how to traverse them.

In practice it means that duplicating an entire array and adding an element to the middle is faster than traversing into half of a linked list and adding an element there (by a lot).

Even if you only add to the end of a linked list, you almost have to have a write-only linked list for it to be worthwhile.

Except... if you have a write-only linked list you create another HUGE problem for yourself... Every insert into a linked list is a memory allocation. Not so with an array. Let's say you have an array that you double in size each time it's full and then duplicate everything in there. Then you insert 1 million items into it. With an array, that's 20 allocations and copies. With a linked list, that's 1 million allocations. No copies, but the extra allocations FAR outweigh the 20 copies.

The only thing where a linked list outperforms an array, is if you have to randomly insert elements into both ends, but in that case, a deque will outperform a linked list again (and a deque is internally implemented as arrays).

1

u/SwishArmyKnife Apr 05 '22

The movie row analogy really makes it make sense. So, if the memory doesn’t necessarily need to be continuous, is there anything that needs to be continuous in relation to node links for the computer to know where the next data point is?

0

u/[deleted] Apr 05 '22

[deleted]

2

u/SwishArmyKnife Apr 05 '22

That makes so much more sense than…whatever I thought was happening. I’m gonna take another look at it and see if I understand it this time. Thanks so much!

1

u/InfiniteBuddy1269 Apr 06 '22

Excellent explanation!

1

u/Xalem Apr 06 '22

Every piece of data sitting in memory has its own memory address. In order for a program to safely write to that address, a basic utility in the operating system allocates memory to code when it asks for it. Your code says, "give me a block of 64 bytes", and the memory utility says, "no problem, your 64 bytes start at address $F620." Those 64 bytes are called a node, and the place in your own code where you store the address $F620 is the pointer.

Think of a linked list as a fancy way of building a stack. This is especially true if you are building the list from the last element of the list. So, with a stack, the only operations you have is to push something on the top stack, and pop an element off the top of the stack. The nice thing is that you can implement a stack as a block of memory, and a single pointer into that memory. And as you add elements, (say 16 bytes worth), the computer internally updates the top of stack pointer to increment by 16. But sometimes, you don't want to set aside a large block of memory. So, you grab just enough memory for a single element which will be the end of your list. (say four bytes for an integer value, and four bytes set to a value that means "nil" And you have a pointer that points to that element, that is the pointer to your list. Then, when you add another element, you grab just a bit more memory, another eight bytes, four for the short integer, and four for the address to the element we mentioned previously(the tail), and you update the pointer to the list to point now to the address of what is now the head. the "pop" functionality is to read the value of the element on your top of stack pointer, and to set the stack pointer to now point to the pointer part of the top element. (oh, yes, and be nice and return the 8 bytes of memory back to the memory utility)

With this you have created a functioning stack, but it isn't implemented as the standard stack. This form of "tail first" way of building lists is used all over functional programming. But sometimes people want to build a list from the first element. Simple enough, you just store two pointers, one to the first element, and one to the last element. When you add a new element, you edit the last element to no longer point to "nil", but rather to the new final element and you update the end pointer to point to the new final element.

This simple way of building a list, I have implemented dozens of times by using an array. Rather than link elements scattered all over memory, I have created an array, and just added elements from Array element zero, one at a time, using a LastElement variable as an index that "points" to the last element using in the array. In fact, think of the act of incrementing the array index as "allocating" an element of the array. (I usually create a little function to increment the array index that is smart enough to test if there is still free space in the array, and if not, resize the array to twice as large.)

Using an array to hold the elements, or allocating each node with a pointer, are the two basic ways of implementing a simple list that does nothing but grow and shrink from one end. The nice thing about the array is that moving from one element to the next is often as simple as incrementing or decrementing the LastElement variable by one. The allocation of nodes as you go can mean that your data is scattered all over your memory (this possible disorganization is why the term for the memory managed by the memory utility that holds a any number of differing elements is called the "heap".) traversing through a list like this means jumping all over memory as the code reads the values. The advantage is that you can build data structures that are more complex than a stack.

The syntax may be throwing you, but, lists, trees, digraphs, stacks, double-linked lists, queues are all built from primitive operations of assigning pointer to point to locations in memory, where there are nodes, which often have their own pointers.

Working with an older language like Pascal (or assembly), you had to keep track of all those pointer assignments as the programmer. If P was a pointer, then P means the value that P points to, and P without the caret means the memory address stored in variable P. Oh, it was often very confusing. And dangerous, if you had direct access to the pointers, a dumb, (or malicious) programmer could change a pointer to any memory address, and start writing data into some other process running on the computer.

Modern languages abstract away the pointers, and give you a list data structure directly, so L could be the list and L=newElement::L could be a way of concatenating a new element as the new head element of list L. The equivalent syntax in another language that gives you stacks might be Push(L , newElement)

1

u/Grination Apr 11 '22

I don't think linked lists by themselves are that interesting of a data structure, but other data structures built using linked lists are useful and have their use cases, such as queues and stacks and resolving collisions in hash tables.