Before learning about a linked list, it helps to first understand a real problem that programmers run into. Once you feel the pain of that problem, the solution makes a lot more sense.
When we write programs, we often need to store a group of related items that we can read one after another, in order. For example, the names of all the students in a class:
Ram Shyam Hari Krishna Neha Nirav
At first this looks easy. Why not just use an array? An array is a row of boxes placed side by side in memory, where each box holds one item. If there are 6 students, we make an array of size 6 and put one name in each box.
This works perfectly... as long as nothing changes.
Imagine a new student, Sundar, joins the class. Now we want 7 names, but our array only has 6 boxes. Can we just add one more box at the end?
No. This is the key limitation: an array's size is fixed when it is created and cannot be changed later. The boxes sit in one continuous stretch of memory, and there is no guarantee that the box right after our array is free.
So the only way to "grow" the array is to do all of this:
7 instead of 6).Sundar into the last box.That is a lot of work just to add one name.
Now imagine Ram leaves the class. We have the same trouble in reverse. We cannot simply remove a box from the middle and have the array close the gap by itself.
Instead we must:
5 instead of 6).Ram.Again, removing one name forces us to rebuild the whole collection.
The examples above added or removed items at the ends. But what if we need to insert or delete a name somewhere in the middle? An array cannot make space in the middle or close a gap in the middle on its own. The items live in side-by-side memory boxes, so you would have to shift many items around or copy everything again. In short, you cannot insert or delete an item in place in an array.
Let's measure how bad this is. We use time complexity (how much work the steps take) and space complexity (how much extra memory we use). Here n means the number of items.
n items when we really needed room for just one is wasteful.Putting it all together, an array is a poor choice when items are added and removed often, because of two built-in limits:
So here is the question that points us forward: what if we had a "magical" data structure that could grow, shrink, and let us insert or delete items anywhere — quickly and without wasting memory? That data structure is the linked list, and that is what we will build next.