Data Structures & Algorithms / Module 1: Linear data structures

Topic 1.2

Linked lists

A chain of nodes pointing at each other: easy to join and break, but walked from the start.

8 min · beginner

Watch: to insert, the computer walks from the first box following the arrows. Once there, only two arrows change.

head38519
  • moving now
  • being checked
  • finished / the result
  • no longer used
Step 1 of 5

Each node holds a value and a pointer to the next node. We only know the first node (head).

To reach a position, a linked list has to walk from head. Once there, inserting only changes two pointers.
insert 7 after position:

Like a treasure hunt

At every stop there is a prize and a note saying "the next stop is at …". You are only told where the first stop is. To reach the fifth stop you have to pass stops one to four and read each note in turn.

Adding a new stop in the middle is easy, though. Make the new stop, write a note pointing to the stop that used to come next, then change the note at the previous stop to point to the new one. No other stop has to move. That is what the figure shows.

The trade-off

OperationLinked listArray
Reading element iO(n), has to walkO(1), direct
Adding at the frontO(1)O(n), everything shifts
Inserting after a node you already holdO(1)O(n)
Finding a valueO(n)O(n)

Note the words "already hold". The insert itself is O(1), but if you first have to find the spot, that search is still O(n). In the figure, inserting after position 3 takes 4 steps of walking, then 2 pointer changes.

Code, for programmersA node, and inserting after it
class Node {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;        // the pointer to the next node
  }
}

function insertAfter(node, value) {
  node.next = new Node(value, node.next);   // two pointers change, nothing moves
}

Quiz

  1. A linked list has 1,000 nodes. How many steps to read node 800?

  2. Adding a new node at the front of a linked list takes…

  3. When does a linked list beat an array?

0 of 3 answered.