Chapter 03 - Linked Lists
Every linked list problem is about rewiring pointers without losing a node. In Rust, it is also about ownership.
This page is the entry point of chapter 3 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
A linked list is a chain of nodes, each one pointing to the next. Reversing a list, removing a node or detecting an intersection all come down to changing a few next pointers in the right order. Two classic tricks: a dummy node in front of the head, which removes the special cases, and two pointers kept a fixed distance apart, which finds the kth node from the end in one pass.
The chapter also has an introduction page with my notes on the key ideas and a checklist.
When to reach for it
- Reversal, removal, merging or reordering of nodes.
- We need the kth node from the end, or the node where two lists meet.
- A cache must evict the least recently used item: hash map plus doubly linked list (LRU cache).
In Rust
- A singly linked list is usually
Option<Box<ListNode>>.Option::take()moves a node out and leavesNonebehind: it is the key to most rewiring. - As soon as two owners point to the same node (doubly linked list, intersection), we need
Rc<RefCell<Node>>, andWeakfor back pointers. - Expect to fight the borrow checker here more than anywhere else in the book. It is normal, and instructive.
Problems in this chapter
- p047 - Introduction: Introduction to the Linked Lists pattern for coding interviews, in Rust: the key idea, when to use it, and the problems of the chapter.
- p050 - Linked List Reversal: Linked List Reversal (Linked Lists), solved in Rust. Reverse a singly linked list.
- p054 - Linked List Reversal Recursive: Linked List Reversal Recursive (Linked Lists), solved in Rust. Reverse a singly linked list.
- p056 - Remove the kth Last Node From a Linked List: Remove the kth Last Node From a Linked List (Linked Lists), solved in Rust. Comments on Rust implementation.
- p060 - Linked List Intersection: Linked List Intersection (Linked Lists) solved in Rust: return the node where two singly linked lists intersect, or none.
- p063 - LRU Cache: LRU Cache (Linked Lists), solved in Rust. Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
- bonus027 - Palindromic Linked List: Palindromic Linked List (Linked Lists), solved in Rust. Given the head of a singly linked list, determine if it is a palindrome.
- bonus031 - Flatten a Multi-Level Linked List: Flatten a Multi-Level Linked List (Linked Lists), solved in Rust. Flatten the multi-level linked list into a single-level linked list by linking the end of…
Other chapters
All the chapters, with every problem, are listed on the series page.