Data Structures
Doubly Linked List
Add to the front or back: O(1) · Find an item: O(n) · Remove a node you already have: O(1), since you don't need to search for its neighbors.
The idea, in plain English
A doubly linked list is like a train. Each car connects to the car in front and the car behind. A regular linked list only lets you walk forward. This one lets you walk backward too.
How it works
- 1Each node stores a value, a link to the next node, and a link to the previous node.
- 2The list remembers both the first node, called the head, and the last node, called the tail.
- 3Walk forward by following .next links, or backward by following .prev links.
When you'd use it
Use this for anything you browse in both directions, like a browser's back and forward history, or a music player's next and previous track.
Common beginner mistakes
- When you insert or remove a node, update both .next and .prev. If you forget one, you break the chain in that direction.
- Remember to update the tail pointer when you add to the end. If you forget, finding the last node needs a slow walk from the head.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Forward: 10 -> 20 -> 30
Backward: 30 -> 20 -> 10See it in motion
A doubly linked list: every node points to the next node AND the previous one.
Not sure this is the right topic? See the learning paths → or where this leads →