Algorithm-Preparation: Arrays and linked lists

Sometimes you need to store a list of elements in memory. Should you use an array, or a linked list?


With arrays, every element must stay with each other in memory. Now suppose you have an array which is 1, 2, 3, 4. You want to add 5 to this array. All you have to do is add 5 after 4 directly, coming close with 4's address. 1, 2, 3, 4, 5 stored in memory continuously.

But what if the address after 4 is taken up by other data? Then you can't just add 5 to that array anymore. It's like going to a movie and finding a place to sit, but you saw your friends already in there, you want to join them, and there's no place for you. You have to move to a new spot where you and your friends all fit. In this case, you need to ask your computer for a different chunk of memory that can fit all five numbers. Then you need to move all your numbers to that place.

One easy fix to this problem is to "hold seats": even if you have only 4 items in your numbers, you can ask the computer for 10 slots, just in case. Then you can add 6 items to your number list without having to move. This is a good container, but you should be aware of downsides:

  1. You may not need the extra slots that you asked for, and then that memory will be wasted. You aren't using it, but no one else can use it either.

  2. You may add more than 10 items to your number list and have to move anyway.


With linked lists, your items can be anywhere in memory. Each item stores the address of the next item in the list. A bunch of random memory addresses are linked together.

It's like a treasure hunt. You go to the first address, and it says, "The next item can be found at address 123." So you go to address 123, and it says, "The next item can be found at address 847," and so on. Adding an item to a linked list is easy: you stick it anywhere in memory and store the address with the previous item.

With linked lists, you never have to move your items. You also avoid another problem. Let's say you go to a popular movie with five of your friends. The six of you are trying to find a place to sit, but the theater is packed. There aren't six seats together. Well, sometimes this happens with arrays. Let's say you're trying to find 10,000 slots for an array. Your memory has 10,000 slots, but it doesn't have 10,000 slots together. You can't get space for your array! A linked list is like saying, "Let's split up and watch the movie."


In general, reading an item from an array needs one operation, but inserting or deleting an item needs n steps. Reading an item from linked list needs n operations, but inserting or deleting an item only needs 1 step.

你可能感兴趣的:(Algorithm-Preparation: Arrays and linked lists)