Lists: How Does it Work?
Lists: How Does it Work?
A list is this big, abstract concept implemented in different ways for different reasons, but it's all about storing data. No matter how you interact with computers and their science, you'll always run into lists because they're a great way to store data all in one place. If you're programming an analysis of the sleeping habits of internet cats or bingeing your favorite independent comedy with a strong female lead on Netflix, you'll see lists.
A list is just a giant group of elements your throw together, and most of the time it's built using either an array or a linked list. When you build a list, you need to be able to
- add an element into any place.
- take out an element from any place.
- traverse every element.
Stacks and queues? They're more special cases. One only lets you see the top of the list and the other only lets you see the ends, but they both count as lists just the same. They give limited access, sure, but they also help control how the data gets used, which can be very powerful in computer science.
In an array, you have direct access to all the elements, but you also have to do much more work if you run out of space. Linked lists are much more flexible, but they also make it tough to find elements in the middle of the list. When you build your stack, queue, or list, you'll need to think about whether it's more important to access things in the middle or have access to any element. That's the way to figure out which data structure you'll use.
Everything else is the details.
Some things cost more in one data structure than they do in another, so you'll need to be careful when picking. But what else is new?
Guidelines
Want easy access to any element in your list? Use an array, or sometimes a linked list if being able to grow your list easily matters too. It's easy to insert at the end of an array, but a bit more difficult in the middle or beginning, so if you use it to implement a stack or a queue, make it so that the top of the stack or the end of the queue is the end of the array. You can thank us later.
If you're implementing a queue, either an array or a linked list will work, you'll just need to keep track of both ends. Stacks can also work well if you need the last things you looked at to come out first and if, like a call stack, you want to show a how things recursively interact. If you want to have things come out in the same order they go in, you can only use a queue.
And that's it. Next time you need to study how a cat-turned-internet-celebrity's sleeping patterns changed based on the added fame, you've got all the list-like data structures you need.
…As long as those data structures store information sequentially.