Doubly linked list
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A doubly linked list gives every item a link to the one before it as well as the one after it. You can walk both directions, and you can remove an item from the middle immediately if you are already holding it, without searching from the start.
Practical use cases
- Web app: Photo gallery Next and Previous buttons. In an image viewer, each photo knows its neighbours. Clicking Next or Previous just follows the link in that direction, and deleting a photo only reconnects its two neighbours. No index numbers need renumbering when the gallery changes, so adding or deleting a photo in the middle of a big album is as quick as at the end.
- Web app: A least-recently-used cache for pages. A site caches the 500 most recently opened product pages. Every time a page is used it moves to the front, and when the cache is full the item at the back is dropped. With two-way links, moving an item takes a few pointer changes, so the cache itself never becomes the slow part.
- System: Browser history and text editors. Browser back and forward buttons are a natural two-way chain of pages, where each page remembers the one before and the one after. Text editors can also keep lines as a chain, so inserting a line in the middle of a big file does not require moving everything after it.
The story: Kabir's Earphone Playlist
Kabir loved his old earphone player. It had a Next button but, strangely, no Previous button. Whenever he wanted to replay the song he had just heard, he had to press Next through the whole playlist and wrap back to the start. Twenty songs of waiting for one song!
His sister Mira opened a library book and shook her head. "The player stores every song as a clue that says only where to go forward. It forgot to store where you came from. Give each song two hands: one holding the song before, one holding the song after."
Kabir rewrote his tiny program so every song had prev and next. Now Previous was one hop backwards. Better still, deleting a song he disliked was easy: the song itself knew both neighbours, so he could join them directly, without searching from the start.
This is a doubly linked list. Each node costs a little more memory (two pointers instead of one), and you must keep both pointers correct on every change. In return you can walk both ways and remove a node you are holding in O(1). Usually the list also remembers a tail, the last node, so you can start from either end.
How to spot this problem, and where you need it
You need to move both forward and backward through items, or remove an item you already have in hand without searching for what comes before it, and a one-way chain makes that awkward.
Signs you need it
- The feature has Previous and Next, back and forward, or undo and redo, so you move in both directions.
- You need to delete or move a known item in the middle quickly, for example in a recently-used cache.
- Your one-way list code keeps walking from the head just to find the item before the one you want.
Where to use it in a project
- LRU caches that move touched entries to the front and evict from the back.
- Carousels, photo galleries, music playlists and browser-style history navigation with previous and next buttons.
- Editors, page builders and lists where lines or blocks are inserted and removed in the middle very often.
The solution
Give each box two links, previous and next, and keep references to both ends. To remove a box you already hold, connect its previous neighbour to its next neighbour and vice versa; the box simply drops out. To insert, wire the new box to its two neighbours. Walking in either direction is a single link follow.
Payoff: Before: walking from the start to find the previous item on every delete. After: reconnecting two links in one step.
Explain it like I am 8
Imagine a line of kids holding hands, but every kid holds both the hand in front and the hand behind. You can walk forward or backward, and if one kid leaves, the two kids beside them just hold each other's hands.
How it works, step by step
- Each node stores
val,prev(the node before) andnext(the node after). - Keep both a
head(first node) and atail(last node). - Append: new.prev = tail, tail.next = new, then tail = new. No walking, because we know the tail.
- Walk forward with
next, or backward from the tail withprev. - Remove a node you hold: connect its prev to its next, and its next back to its prev. Fix head or tail if the node was at an end.
The code in four languages
PHP
<?php
class DNode {
public $val;
public ?DNode $prev = null; // the song before
public ?DNode $next = null; // the song after
public function __construct($val) { $this->val = $val; }
}
class DoublyLinkedList {
public ?DNode $head = null;
public ?DNode $tail = null;
public function append($val): DNode { // O(1) thanks to the tail
$node = new DNode($val);
if ($this->tail === null) { $this->head = $this->tail = $node; return $node; }
$node->prev = $this->tail;
$this->tail->next = $node;
$this->tail = $node;
return $node;
}
public function remove(DNode $node): void { // O(1): we already hold the node
if ($node->prev !== null) $node->prev->next = $node->next; else $this->head = $node->next;
if ($node->next !== null) $node->next->prev = $node->prev; else $this->tail = $node->prev;
$node->prev = $node->next = null;
}
public function forward(): array {
$out = [];
for ($c = $this->head; $c !== null; $c = $c->next) $out[] = $c->val;
return $out;
}
public function backward(): array {
$out = [];
for ($c = $this->tail; $c !== null; $c = $c->prev) $out[] = $c->val;
return $out;
}
}
$pl = new DoublyLinkedList();
$pl->append('Raag');
$lofi = $pl->append('Lofi');
$pl->append('Bhajan');
$pl->append('Pop');
echo 'Forward : ' . implode(', ', $pl->forward()) . "\n"; // Raag, Lofi, Bhajan, Pop
echo 'Backward: ' . implode(', ', $pl->backward()) . "\n"; // Pop, Bhajan, Lofi, Raag
$pl->remove($lofi);
echo 'After removing Lofi: ' . implode(', ', $pl->forward()) . "\n"; // Raag, Bhajan, Pop
echo 'Backward again : ' . implode(', ', $pl->backward()) . "\n"; // Pop, Bhajan, RaagJavaScript
class DNode {
constructor(val) {
this.val = val;
this.prev = null; // the song before
this.next = null; // the song after
}
}
class DoublyLinkedList {
constructor() { this.head = null; this.tail = null; }
append(val) { // O(1) thanks to the tail
const node = new DNode(val);
if (this.tail === null) { this.head = this.tail = node; return node; }
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
return node;
}
remove(node) { // O(1): we already hold the node
if (node.prev !== null) node.prev.next = node.next; else this.head = node.next;
if (node.next !== null) node.next.prev = node.prev; else this.tail = node.prev;
node.prev = node.next = null;
}
forward() {
const out = [];
for (let c = this.head; c !== null; c = c.next) out.push(c.val);
return out;
}
backward() {
const out = [];
for (let c = this.tail; c !== null; c = c.prev) out.push(c.val);
return out;
}
}
const pl = new DoublyLinkedList();
pl.append('Raag');
const lofi = pl.append('Lofi');
pl.append('Bhajan');
pl.append('Pop');
console.log('Forward : ' + pl.forward().join(', ')); // Raag, Lofi, Bhajan, Pop
console.log('Backward: ' + pl.backward().join(', ')); // Pop, Bhajan, Lofi, Raag
pl.remove(lofi);
console.log('After removing Lofi: ' + pl.forward().join(', ')); // Raag, Bhajan, Pop
console.log('Backward again : ' + pl.backward().join(', ')); // Pop, Bhajan, RaagJava
import java.util.*;
public class Main {
static class DNode {
String val;
DNode prev = null; // the song before
DNode next = null; // the song after
DNode(String val) { this.val = val; }
}
static class DoublyLinkedList {
DNode head = null;
DNode tail = null;
DNode append(String val) { // O(1) thanks to the tail
DNode node = new DNode(val);
if (tail == null) { head = tail = node; return node; }
node.prev = tail;
tail.next = node;
tail = node;
return node;
}
void remove(DNode node) { // O(1): we already hold the node
if (node.prev != null) node.prev.next = node.next; else head = node.next;
if (node.next != null) node.next.prev = node.prev; else tail = node.prev;
node.prev = node.next = null;
}
List<String> forward() {
List<String> out = new ArrayList<>();
for (DNode c = head; c != null; c = c.next) out.add(c.val);
return out;
}
List<String> backward() {
List<String> out = new ArrayList<>();
for (DNode c = tail; c != null; c = c.prev) out.add(c.val);
return out;
}
}
public static void main(String[] args) {
DoublyLinkedList pl = new DoublyLinkedList();
pl.append("Raag");
DNode lofi = pl.append("Lofi");
pl.append("Bhajan");
pl.append("Pop");
System.out.println("Forward : " + String.join(", ", pl.forward())); // Raag, Lofi, Bhajan, Pop
System.out.println("Backward: " + String.join(", ", pl.backward())); // Pop, Bhajan, Lofi, Raag
pl.remove(lofi);
System.out.println("After removing Lofi: " + String.join(", ", pl.forward())); // Raag, Bhajan, Pop
System.out.println("Backward again : " + String.join(", ", pl.backward())); // Pop, Bhajan, Raag
}
}Go
package main
import (
"fmt"
"strings"
)
type DNode struct {
val string
prev *DNode // the song before
next *DNode // the song after
}
type DoublyLinkedList struct {
head *DNode
tail *DNode
}
func (l *DoublyLinkedList) Append(val string) *DNode { // O(1) thanks to the tail
node := &DNode{val: val}
if l.tail == nil {
l.head, l.tail = node, node
return node
}
node.prev = l.tail
l.tail.next = node
l.tail = node
return node
}
func (l *DoublyLinkedList) Remove(node *DNode) { // O(1): we already hold the node
if node.prev != nil {
node.prev.next = node.next
} else {
l.head = node.next
}
if node.next != nil {
node.next.prev = node.prev
} else {
l.tail = node.prev
}
node.prev, node.next = nil, nil
}
func (l *DoublyLinkedList) Forward() []string {
var out []string
for c := l.head; c != nil; c = c.next {
out = append(out, c.val)
}
return out
}
func (l *DoublyLinkedList) Backward() []string {
var out []string
for c := l.tail; c != nil; c = c.prev {
out = append(out, c.val)
}
return out
}
func main() {
pl := &DoublyLinkedList{}
pl.Append("Raag")
lofi := pl.Append("Lofi")
pl.Append("Bhajan")
pl.Append("Pop")
fmt.Println("Forward :", strings.Join(pl.Forward(), ", ")) // Raag, Lofi, Bhajan, Pop
fmt.Println("Backward:", strings.Join(pl.Backward(), ", ")) // Pop, Bhajan, Lofi, Raag
pl.Remove(lofi)
fmt.Println("After removing Lofi:", strings.Join(pl.Forward(), ", ")) // Raag, Bhajan, Pop
fmt.Println("Backward again :", strings.Join(pl.Backward(), ", ")) // Pop, Bhajan, Raag
}Time: O(1) at either end and removal of a held node; O(n) to search · Extra space: O(n). Two pointers per node cost extra memory, but they buy you backward walking and instant removal.
Watch out for
- Updating only one direction: setting
a.next = bbut forgettingb.prev = aleaves the list broken when walked backward. - Forgetting to update
headortailwhen you remove the first or last node. - Thinking removal by value is O(1). Finding the node is still a walk; only unlinking a node you already hold is instant.
Quick check
- What extra thing does each node of a doubly linked list store?
- A pointer to the previous node
- A copy of the whole list
- The index number
- A counter of visits
- You hold a node in the middle of a doubly linked list. How long does removing it take?
- O(n)
- O(n²)
- O(log n)
- O(1)
- What is the price of a doubly linked list compared with a singly one?
- Slower searching by value
- It cannot be walked forward
- More memory and more pointers to keep correct
- It must be sorted