26
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.” If there’s space in memory, you have space for
your linked list.
If linked lists are so much better at inserts, what are arrays good for?
Arrays
Websites with top-10 lists use a scummy tactic to get more page views.
Instead of showing you the list on one page, they put one item on each
page and make you click Next to get to the next item in the list. For
example, Top 10 Best TV Villains won’t show you the entire list on one
page. Instead, you start at #10 (Newman), and you have to click Next on
each page to reach #1 (Gustavo Fring). This technique gives the websites
10 whole pages on which to show you ads, but it’s boring to click Next 9
times to get to #1. It would be much better if the whole list was on one
page and you could click each person’s name for more info.
Linked lists have a similar problem. Suppose you want to read the last
item in a linked list. You can’t just read it, because you don’t know what
address it’s at. Instead, you have to go to item #1 to get the address for
Dostları ilə paylaş: