Arrays are great when we need to access elements quickly using their indices.
But they have a limitation.
Imagine you have an array with thousands of elements, and you want to insert a new element at the beginning. To make room, you might need to shift every existing element one position to the right. And if you're doing this frequently, it can become expensive.
But what if we could insert or delete elements without having to shift everything around?
That's where linked lists come in.
In this chapter, we'll break down what a linked list is, how it works internally, its core operations, their time and space complexities, and the different types of linked lists. We'll also discuss some common linked list patterns you'll encounter in coding interviews.
A linked list is a linear data structure made up of individual elements called nodes.
Unlike an array, where elements are stored next to each other in memory, nodes in a linked list don't need to be stored in consecutive memory locations.
Instead, each node contains two things:
These references connect the nodes together, forming a chain.
For example, imagine a linked list containing four values: 10, 20, 30, and 40.
The first node stores 10 and points to the node containing 20. That node points to 30, which then points to 40. And since 40 is the last node, its next reference is null.
That's the basic structure of a singly linked list.
Now, here's an interesting question. If these nodes can be stored anywhere in memory, how do we know where the list begins?
For that, we maintain a reference called the head. The head points to the first node in the list. And from there, we can follow the next references to reach every other node.
The head is our only way into the list. If we lose it and have no other reference to the nodes, we lose access to the entire list.
Two small cases are worth keeping in mind:
null.null.Now, let's see what a linked list looks like in code.
We can define a node like this. Each node stores an integer value and a reference to the next node.
Now, suppose we want to create a linked list containing 10, 20, and 30. We create three nodes and connect them using their next references:
And that's it. We now have a linked list that we can access starting from the head.
Let's understand what makes linked lists different from arrays at the memory level.
In an array, elements are stored in contiguous memory locations.
Array (contiguous memory)
If we know the starting address and an element's index, we can calculate exactly where that element is stored. With 4-byte integers starting at address 1000, the element at index 3 sits at 1000 + 3 × 4 = 1012. That's why accessing an array element takes constant time.
Linked lists work differently. Each node is allocated independently and can be stored anywhere in memory. The nodes are connected through references rather than their physical locations.
Linked list (nodes anywhere in memory)
So, if we want to access the fourth element, we can't jump directly to it. We have to start at the head and follow the references, one node at a time, until we reach the fourth node.
And this difference has a big impact on the performance of linked list operations.
The most common operations on a linked list are traversal, searching, insertion, and deletion.
Suppose we want to print every value in our linked list.
We begin with a pointer called current, which initially points to the head. We print the value of the current node, then move to the next node. And we keep doing this until current becomes null.
Since we visit every node once, traversal takes O(n) time, where n is the number of nodes. And because we only use one additional pointer, the extra space complexity is O(1).
Searching for a particular value works similarly.
Suppose we're looking for 40. We start at the head and compare each node's value with 40. We continue until we find it or reach the end.
In the worst case, we might have to check every node, so searching also takes O(n) time.
Accessing an element by its position works the same way. To reach index 3, we start at the head and move forward three times, so access by index also takes O(n) time in the worst case.
Now, let's look at where linked lists really become useful.
Suppose our linked list contains 10, 20, and 30, and we want to insert 5 at the beginning.
With an array, we might need to shift all the existing elements. But with a linked list, we only need to change a couple of references:
And we're done. Our list now contains 5, 10, 20, and 30, and we didn't have to move any existing nodes.
No matter how large the list is, inserting at the beginning takes O(1) time.
Now, what if we want to insert a node at the end? Suppose we want to add 40 to the list 10, 20, 30.
We create a new node, traverse the list to find the last node, and update its next reference.
The important part here is finding the last node. If we only have the head, we need to traverse the entire list. So, inserting at the end takes O(n) time.
But there's a simple optimization. We can maintain another reference called the tail, which always points to the last node. This lets us append a new node directly, without traversing the list: we set tail.next to the new node, then move tail to it.
With a properly maintained tail reference, insertion at the end takes O(1) time.
Now, let's say we want to insert 25 between 20 and 30.
Here, current is the node containing 20:
Notice the order of the last two steps. We connect the new node to the rest of the list before changing the previous node's reference. If we updated 20's next reference first, we would lose the only reference to 30, and with it, every node after it.
Once we know where to insert, updating the references takes O(1) time. But finding that position can take O(n) time. So, inserting at an arbitrary position takes O(n) time overall.
Suppose our linked list contains 10, 20, 30, and 40, and we want to remove the first node.
This is actually very simple. We just update the head to point to the second node.
The original first node is now disconnected from our list. In languages with automatic garbage collection, its memory can eventually be reclaimed if nothing else references it. In C++, we free it ourselves.
We didn't have to shift any elements or traverse the list. So, deleting the first node takes O(1) time.
Of course, we should first make sure the list isn't empty. That's what the null check is for.
Now, what if we want to delete the node containing 30?
We can't simply remove it and expect the other nodes to reconnect automatically. Instead, we need to update the previous node's next reference.
We traverse the list until we reach the node containing 20. Then we make that node point directly to 40, effectively skipping 30. And that's it. The node containing 30 is no longer part of our list.
The reference update itself takes O(1) time. But finding the previous node can take O(n) time. That's why deleting a node by value or position generally takes O(n) time.
However, if we already have a reference to the previous node, we can remove the next node in constant time.
So far, we've been working with singly linked lists, where each node points only to the next node.
But there are a few other variations worth knowing.
In a doubly linked list, each node stores three things: the data, a reference to the next node, and a reference to the previous node.
This means we can traverse the list in both directions. We can move forward using the next reference or backward using the previous reference.
This can be useful for features like browser history, where we want to navigate backward and forward. Text editors use the same idea for undo and redo, and LRU caches use a doubly linked list to move entries around in constant time.
It also makes deleting a known node easier because we can directly access its previous node.
But there's a trade-off. Each node needs extra memory for the previous reference, and insertion and deletion involve updating more connections.
Another variation is a circular linked list.
In a regular linked list, the last node points to null. But in a circular linked list, the last node points back to the first node. So, instead of ending, the list forms a loop.
This can be useful when we need to repeatedly cycle through a collection of elements. For example, a round-robin scheduler that cycles through a set of tasks. Once we reach the last task, we can return to the first.
Circular linked lists can be singly or doubly linked.
One thing to watch for: since no node points to null, a traversal can't stop when it reaches null. It stops when it gets back to the node it started from, usually the head. Otherwise, it would keep going around the loop forever.
Now that we understand how linked lists work, let's compare them with arrays.
Both are used to store collections of elements in a particular order. But they have different strengths and weaknesses.
Arrays give us O(1) access by index because their elements are stored in contiguous memory. Linked lists, on the other hand, require O(n) time to reach an arbitrary position.
However, linked lists can insert or delete nodes in O(1) time when we already have the necessary references. With arrays, we might need to shift elements, which can take O(n) time.
Arrays are also generally more memory-efficient because they don't need an extra reference for every element. And because their elements are stored together in memory, they often benefit from better CPU cache performance.
So, linked lists aren't necessarily better than arrays. The right choice depends on how we need to access and modify our data.
Let's quickly summarize the time complexities of common singly linked list operations.
In terms of space, storing n nodes requires O(n) space. But linked lists also need additional memory for the references connecting those nodes.
And remember, insertion and deletion take constant time only when we already have the necessary node references. Finding those nodes is often what takes the most time.
A doubly linked list with a tail reference can also delete the last node in O(1) time, because the tail's prev reference leads straight to the new last node. A singly linked list has to walk from the head to find it.
Linked list problems are common in coding interviews because they test how well you understand references and pointer manipulation.
One of the most popular problems is reversing a linked list. Instead of creating a new list, we reverse the direction of the existing connections.
The algorithm walks the list once with three pointers:
prev: the node that was before curr (starts as null).curr: the node currently being processed (starts as head).next: the node after curr, saved before we overwrite curr.next.At each step, we flip curr.next to point to prev, then move all three pointers one step forward.
Tracing through 1 → 2 → 3 → null:
The loop exits when curr becomes null, leaving prev at the new head (3). The whole operation takes O(n) time and O(1) space.
Another common problem is finding the middle node.
This introduces an important technique called Fast and Slow Pointers. We move one pointer one step at a time and the other two steps at a time. By the time the faster pointer reaches the end, the slower pointer will be at the middle.
For a list 1 → 2 → 3 → 4 → 5, after two iterations slow is at 3 and fast is at 5, so slow points to the middle. For an even-length list 1 → 2 → 3 → 4, this returns the second middle (3). A small change to the loop condition returns the first middle instead.
This same technique can also help us detect cycles in a linked list.
If the list has a cycle, the fast pointer keeps going around the loop. Each iteration, the gap between fast and slow closes by one node, so sooner or later they land on the same node. If there's no cycle, the fast pointer reaches null and the loop ends.
Both of these run in O(n) time and O(1) extra space.
Other popular problems include merging two sorted lists, removing the nth node from the end, and finding where two linked lists intersect. We'll explore these patterns in more detail in upcoming lessons.
Before we wrap up, let's quickly cover a few common mistakes to avoid.
1. Losing references while changing connections. When inserting or deleting nodes, the order in which you update pointers matters. A wrong update could disconnect part of your list. When inserting, connect the new node to the rest of the list first, then update the previous node.
2. Forgetting to handle empty lists. Always consider what happens when the head is null.
3. Overlooking single-node lists. Some operations need special handling when there's only one node. For example, deleting the only node must leave the head, and the tail if you keep one, set to null.
4. Not updating the head or tail. Don't forget to update the head or tail when inserting or deleting nodes at the boundaries. A common trick is a dummy node placed before the head, which lets you treat the first node like any other and removes most of these special cases.
5. Careless traversal conditions. Be careful with traversal conditions. Trying to access current.next when current is null can cause a null reference error.
These mistakes become much easier to avoid with practice.
And that's your introduction to linked lists.
To make these concepts stick, try implementing a singly linked list from scratch.
Then challenge yourself to reverse a linked list without using any additional data structures.
Once you're comfortable working with these references, many linked list interview problems will become much easier to understand and solve.
10 quizzes