Doubly linked lists and deques
Reaching both ends in constant time: last pointers, backward links, two sentinels and then one circular sentinel, who owns whom when links point both ways, and the deque interface that Projects 6 and 7 implement.
- CS61B
- DLLists · Textbook Ch. 6
- Swift book
- Automatic Reference Counting
- Documentation
- Swift Collections
The SLList from Lesson 28 adds to the front instantly, but addLast walks
the whole list. This lesson follows CS61B’s path from there to a list that
is fast at both ends, and in Swift that path has one extra step CS61B
never needs: deciding which node owns which, so the list can be freed.
A pointer to the last node
The obvious fix is to remember the last node, just as the list remembers its size:
private var last: IntNode // the sentinel when the list is empty
func addLast(_ item: Int) {
last.next = IntNode(item, nil)
last = last.next!
size += 1
}
Now addLast takes constant time. But try removeLast. It must make the
second-to-last node the new last node, and a singly linked node has no
way back: finding it still means walking from the front. A pointer to the
second-to-last node would not help either, since after one removal we would
need the third-to-last, and so on.
Links in both directions
The fix is to give every node a link backward too. A doubly linked list
node has an item, a next, and a prev:
sentinel ⇄ [1] ⇄ [2] ⇄ [3]
From the last node, prev reaches the one before it in one step, so both
ends can add and remove in constant time. The price is one more reference per
node, and twice as many links to keep consistent in every operation.
Where does last point?
A new special case appears. When the list is empty, last must point at the
sentinel; otherwise at a real node. Code that treats the last node as an
item, like getLast, has to check which. CS61B shows two ways out:
- Two sentinels, one at each end. The first item is always
front.nextand the last is alwaysback.prev, and an empty list is the two sentinels pointing at each other. - One circular sentinel. The list forms a ring: the sentinel’s
nextis the first item, and itsprevis the last. An empty list is a sentinel whosenextandprevare itself.
Either way, every real node has a node on both sides, and adding or removing is the same four link updates everywhere. CS61B recommends the circular sentinel, and so do we. But in Swift, a ring of nodes needs care.
Who owns whom
Lesson 25’s ARC frees an object when no strong references point to it. In a
doubly linked list, every pair of neighbors points at each other: node 1’s
next holds node 2, and node 2’s prev holds node 1. If both links are
strong, that is a cycle, and when the list goes away, no node is ever freed.
The same rule from Lesson 25 applies: decide who owns whom. Links
forward own the next node; links backward only refer to the previous one, so
they are weak:
private final class Node {
var item: Element?
var next: Node! // strong: each node keeps the next one alive
weak var prev: Node! // weak: a back link is not ownership
init(_ item: Element?) {
self.item = item
}
}
Node! is an implicitly unwrapped optional: an optional that Swift
unwraps automatically where it is used. It fits here because the links are
nil only for an instant, while a node is being created; after that, in a
circular list, every node always has both neighbors.
That handles the pairs, but a circular list has one more cycle: the ring of
next links itself, which goes all the way around through the sentinel and
back. The list breaks it when it is freed:
deinit {
sentinel.next = nil // cut the ring
}
With the ring cut, nothing strong points at the first node anymore, so it is
freed; that releases its next, which is freed in turn, all the way round
to the last node, which releases the sentinel. The nodes are private, so
nothing outside the list can be holding on to one of them, and cutting the
ring always frees everything.
A generic circular deque
A deque (pronounced “deck”, short for double-ended queue) is a list that
supports adding and removing at both ends. Here it is, with the four link
updates written once each, in insert(_:after:) and remove(_:):
var liveNodes = 0 // for demonstration only
final class LinkedListDeque<Element> {
private final class Node {
var item: Element?
var next: Node!
weak var prev: Node!
init(_ item: Element?) {
self.item = item
liveNodes += 1
}
deinit {
liveNodes -= 1
}
}
private let sentinel = Node(nil)
private(set) var count = 0
init() {
sentinel.next = sentinel
sentinel.prev = sentinel
}
deinit {
sentinel.next = nil
}
var isEmpty: Bool { count == 0 }
func addFirst(_ item: Element) {
insert(item, after: sentinel)
}
func addLast(_ item: Element) {
insert(item, after: sentinel.prev)
}
func removeFirst() -> Element? {
isEmpty ? nil : remove(sentinel.next)
}
func removeLast() -> Element? {
isEmpty ? nil : remove(sentinel.prev)
}
var items: [Element] {
var result: [Element] = []
var node = sentinel.next!
while node !== sentinel {
result.append(node.item!)
node = node.next
}
return result
}
private func insert(_ item: Element, after node: Node) {
let new = Node(item)
new.prev = node
new.next = node.next
node.next.prev = new
node.next = new
count += 1
}
private func remove(_ node: Node) -> Element {
node.prev.next = node.next
node.next.prev = node.prev
count -= 1
return node.item!
}
}
do {
let deque = LinkedListDeque<Int>()
for n in 1...5 {
deque.addLast(n)
}
deque.addFirst(0)
print(deque.removeFirst()!, deque.removeLast()!, deque.items, liveNodes)
}
print(liveNodes)
// 0 5 [1, 2, 3, 4] 5
// 0
Inside the do block there are five nodes alive: the sentinel and four
items. After the block, the deque is gone, and so are all its nodes. Delete
the deinit, and the second line prints 5: the ring keeps itself alive
forever.
Three details are worth a second look:
addLastisinsert(item, after: sentinel.prev): “after the last node”. For an empty list,sentinel.previs the sentinel itself, so the same line works with no special case.- In
insert, the order of the four assignments matters.new.next = node.nextmust readnode.nextbefore the last line replaces it. - The loop in
itemsstops when it comes back around to the sentinel, compared by identity with!==.
What would Swift print?
final class Node {
var next: Node?
weak var prev: Node?
}
var a: Node? = Node()
let b = Node()
a!.next = b
b.prev = a
a = nil
print(b.prev == nil)Show answer and explanation
Answertrue
The only strong reference to the first node was a. b.prev is weak, so it
does not keep the node alive, and it becomes nil automatically when the node
is freed.
The deque interface
Projects 6 and 7 build this deque twice, with a linked list and then with an
array, and test both with the same tests. What they share is an
interface, written as a protocol. CS61B’s is called Deque61B; ours has
the same operations:
protocol Deque<Element> {
associatedtype Element
var count: Int { get }
var isEmpty: Bool { get }
mutating func addFirst(_ item: Element)
mutating func addLast(_ item: Element)
mutating func removeFirst() -> Element?
mutating func removeLast() -> Element?
/// The item at `index`, counting from the front, or nil if out of range.
func get(_ index: Int) -> Element?
/// All the items, front to back.
func toArray() -> [Element]
}
protocol Deque<Element> declares Element as the protocol’s primary
associated type, which lets code write some Deque<Int> or
any Deque<String>, just as with some Collection<Int>. Lesson 31 is all
about interfaces like this one; for now, notice that nothing in it mentions
nodes or arrays. The protocol is what users of a deque depend on, and
Projects 6 and 7 are two different ways of keeping its promises.
What each operation costs
| Operation | SLList (Lesson 28) |
circular LinkedListDeque |
|---|---|---|
addFirst, removeFirst |
constant | constant |
addLast |
walks the whole list | constant |
removeLast |
walks the whole list | constant |
get(i) |
walks i nodes |
walks up to half the list |
get is still slow for a linked list, whatever we do. There is no way to
jump to the middle of a chain of references, and that is the problem Lesson
30’s arrays solve.
Put the lines in order
Put the lines in order so the program prints [1, 2].
first.next = secondfinal class Node {}print([second.prev!.item, first.next!.item])let item: Intvar next: Node?let first = Node(1)weak var prev: Node?second.prev = firstlet second = Node(2)init(_ item: Int) { self.item = item }
Show the correct program
final class Node {
let item: Int
var next: Node?
weak var prev: Node?
init(_ item: Int) { self.item = item }
}
let first = Node(1)
let second = Node(2)
first.next = second
second.prev = first
print([second.prev!.item, first.next!.item])Lab 28: Doubly linked lists
Q0: What would Swift print?
What would Swift print?
var alive = 0
final class Node {
var next: Node?
var prev: Node?
init() { alive += 1 }
deinit { alive -= 1 }
}
var a: Node? = Node()
var b: Node? = Node()
a!.next = b
b!.prev = a
a = nil
b = nil
print(alive)Show answer and explanation
Answer2
Both links are strong, so the two nodes keep each other alive after the
variables are cleared: a leak. With weak var prev, this prints 0.
What would Swift print?
final class Node {
var label: String
var next: Node!
weak var prev: Node!
init(_ label: String) { self.label = label }
}
let s = Node("s")
s.next = s
s.prev = s
let x = Node("x")
x.prev = s
x.next = s.next
s.next.prev = x
s.next = x
print(s.next.label, s.prev.label, x.next.label, x.prev.label)Show answer and explanation
Answerx x s s
Inserting after the sentinel of an empty circular list makes x both the
first and the last node: the sentinel’s next and prev both point at it,
and its own next and prev both point back at the sentinel.
Q1: Two sentinels
Write TwoSentinelList, a doubly linked list of Ints with separate front
and back sentinels, supporting addFirst, addLast, removeFirst,
removeLast, and items. Decide which links are weak so that nothing
leaks, and check with a live-node counter.
Show solution
var liveNodes = 0
final class TwoSentinelList {
private final class Node {
var item: Int
var next: Node?
weak var prev: Node?
init(_ item: Int) {
self.item = item
liveNodes += 1
}
deinit {
liveNodes -= 1
}
}
private let front = Node(0)
private let back = Node(0)
private(set) var count = 0
init() {
front.next = back
back.prev = front
}
func addFirst(_ item: Int) {
insert(item, after: front)
}
func addLast(_ item: Int) {
insert(item, after: back.prev!)
}
func removeFirst() -> Int? {
count == 0 ? nil : remove(front.next!)
}
func removeLast() -> Int? {
count == 0 ? nil : remove(back.prev!)
}
var items: [Int] {
var result: [Int] = []
var node = front.next!
while node !== back {
result.append(node.item)
node = node.next!
}
return result
}
private func insert(_ item: Int, after node: Node) {
let new = Node(item)
new.prev = node
new.next = node.next
node.next!.prev = new
node.next = new
count += 1
}
private func remove(_ node: Node) -> Int {
node.prev!.next = node.next
node.next!.prev = node.prev
count -= 1
return node.item
}
}
var list: TwoSentinelList? = TwoSentinelList()
list!.addLast(2)
list!.addFirst(1)
list!.addLast(3)
assert(list!.removeLast() == 3 && list!.items == [1, 2])
assert(liveNodes == 4) // two sentinels and two items
list = nil
assert(liveNodes == 0)The strong next links form a chain from front to back that does not come
back around, so there is no ring to cut: when the list goes away, front is
freed, then each node in turn. The two sentinels are one extra node compared
with the circular design, which is the trade CS61B describes.
Q2: get from the nearer end
Add get(_:) to LinkedListDeque, returning nil for an index out of
range. Walk forward from the sentinel for indices in the first half and
backward for the second half, so no call walks more than half the list.
Show solution
final class LinkedListDeque<Element> {
private final class Node {
var item: Element?
var next: Node!
weak var prev: Node!
init(_ item: Element?) {
self.item = item
}
}
private let sentinel = Node(nil)
private(set) var count = 0
init() {
sentinel.next = sentinel
sentinel.prev = sentinel
}
deinit {
sentinel.next = nil
}
func addLast(_ item: Element) {
let new = Node(item)
let last = sentinel.prev!
new.prev = last
new.next = sentinel
last.next = new
sentinel.prev = new
count += 1
}
func get(_ index: Int) -> Element? {
guard (0..<count).contains(index) else {
return nil
}
var node: Node
if index < count / 2 {
node = sentinel.next
for _ in 0..<index {
node = node.next
}
} else {
node = sentinel.prev
for _ in 0..<(count - 1 - index) {
node = node.prev
}
}
return node.item
}
}
let deque = LinkedListDeque<String>()
for word in ["a", "b", "c", "d", "e"] {
deque.addLast(word)
}
assert(deque.get(0) == "a" && deque.get(1) == "b" && deque.get(3) == "d" && deque.get(4) == "e")
assert(deque.get(5) == nil && deque.get(-1) == nil)Index i is count - 1 - i steps from the back. The bounds check comes
first, so both loops can assume the node they reach is a real one.
Q3: get, recursively
CS61B’s project also asks for a recursive getRecursive(_:). Write it with a
private helper that takes a node and the number of steps left to go.
Show solution
final class LinkedListDeque<Element> {
private final class Node {
var item: Element?
var next: Node!
weak var prev: Node!
init(_ item: Element?) {
self.item = item
}
}
private let sentinel = Node(nil)
private(set) var count = 0
init() {
sentinel.next = sentinel
sentinel.prev = sentinel
}
deinit {
sentinel.next = nil
}
func addFirst(_ item: Element) {
let new = Node(item)
new.prev = sentinel
new.next = sentinel.next
sentinel.next.prev = new
sentinel.next = new
count += 1
}
func getRecursive(_ index: Int) -> Element? {
guard (0..<count).contains(index) else {
return nil
}
return item(from: sentinel.next, steps: index)
}
private func item(from node: Node, steps: Int) -> Element? {
steps == 0 ? node.item : item(from: node.next, steps: steps - 1)
}
}
let deque = LinkedListDeque<Int>()
for n in (1...4).reversed() {
deque.addFirst(n)
}
assert(deque.getRecursive(0) == 1 && deque.getRecursive(3) == 4 && deque.getRecursive(4) == nil)The public method checks the bounds once; the helper can then assume every
step lands on a real node. As Lesson 28 warned, the recursion is as deep as the
index, so the iterative get is the one to use for long lists.
Q4: Randomized comparison
Using the LinkedListDeque from this lesson, write a randomized test that
performs 10,000 random operations among addFirst, addLast,
removeFirst, and removeLast, comparing with a Swift array after each
one, and checking at the end that no nodes leak.
Show solution
var liveNodes = 0
final class LinkedListDeque<Element> {
private final class Node {
var item: Element?
var next: Node!
weak var prev: Node!
init(_ item: Element?) {
self.item = item
liveNodes += 1
}
deinit {
liveNodes -= 1
}
}
private let sentinel = Node(nil)
private(set) var count = 0
init() {
sentinel.next = sentinel
sentinel.prev = sentinel
}
deinit {
sentinel.next = nil
}
func addFirst(_ item: Element) { insert(item, after: sentinel) }
func addLast(_ item: Element) { insert(item, after: sentinel.prev) }
func removeFirst() -> Element? { count == 0 ? nil : remove(sentinel.next) }
func removeLast() -> Element? { count == 0 ? nil : remove(sentinel.prev) }
private func insert(_ item: Element, after node: Node) {
let new = Node(item)
new.prev = node
new.next = node.next
node.next.prev = new
node.next = new
count += 1
}
private func remove(_ node: Node) -> Element {
node.prev.next = node.next
node.next.prev = node.prev
count -= 1
return node.item!
}
}
var deque: LinkedListDeque<Int>? = LinkedListDeque()
var reference: [Int] = []
var random = SystemRandomNumberGenerator()
for n in 0..<10_000 {
switch Int.random(in: 0..<4, using: &random) {
case 0:
deque!.addFirst(n)
reference.insert(n, at: 0)
case 1:
deque!.addLast(n)
reference.append(n)
case 2:
assert(deque!.removeFirst() == (reference.isEmpty ? nil : reference.removeFirst()))
default:
assert(deque!.removeLast() == reference.popLast())
}
assert(deque!.count == reference.count)
assert(liveNodes == reference.count + 1) // the items and the sentinel
}
deque = nil
assert(liveNodes == 0)Checking the live-node count at every step also catches a removed node that is still reachable, which a comparison of items alone would miss.
Q5: Rotate
Add rotate(by:), which moves the first k items to the back, one at a time
with removeFirst and addLast. Then write rotateByRelinking(by:), which
does the same by moving the sentinel within the ring instead, without
creating or freeing any nodes. What does each cost?
Show solution
final class LinkedListDeque<Element> {
private final class Node {
var item: Element?
var next: Node!
weak var prev: Node!
init(_ item: Element?) {
self.item = item
}
}
private let sentinel = Node(nil)
private(set) var count = 0
init() {
sentinel.next = sentinel
sentinel.prev = sentinel
}
deinit {
sentinel.next = nil
}
func addLast(_ item: Element) {
let new = Node(item)
new.prev = sentinel.prev
new.next = sentinel
sentinel.prev.next = new
sentinel.prev = new
count += 1
}
func removeFirst() -> Element? {
guard count > 0 else { return nil }
let first = sentinel.next!
sentinel.next = first.next
first.next.prev = sentinel
count -= 1
return first.item
}
func rotate(by k: Int) {
for _ in 0..<k {
if let item = removeFirst() {
addLast(item)
}
}
}
func rotateByRelinking(by k: Int) {
guard count > 1, k % count != 0 else { return }
// Take the sentinel out of the ring...
let first = sentinel.next!
let last = sentinel.prev!
last.next = first
first.prev = last
// ...walk to the node that should become the last one...
var newLast = last
for _ in 0..<(k % count) {
newLast = newLast.next
}
// ...and put the sentinel back in after it.
let newFirst = newLast.next!
newLast.next = sentinel
sentinel.prev = newLast
sentinel.next = newFirst
newFirst.prev = sentinel
}
var items: [Element] {
var result: [Element] = []
var node = sentinel.next!
while node !== sentinel {
result.append(node.item!)
node = node.next
}
return result
}
}
let a = LinkedListDeque<Int>()
let b = LinkedListDeque<Int>()
for n in 1...5 {
a.addLast(n)
b.addLast(n)
}
a.rotate(by: 2)
b.rotateByRelinking(by: 7) // 7 is 2 more than a full turn
assert(a.items == [3, 4, 5, 1, 2] && b.items == a.items)Both take time proportional to k, but the first creates and frees k
nodes, while the second only walks and changes four links at the end. Taking
k % count first also makes a rotation by a million cost no more than one
full turn.
Q6 (optional): A least-recently-used cache
A cache keeps the results of expensive work, up to some capacity. When
it is full, a least-recently-used (LRU) cache throws away the entry that
was used longest ago. Write LRUCache with get(_:) and set(_:_:), both in
constant time, by combining a dictionary from keys to nodes with a doubly
linked list kept in order of use.
Show solution
final class LRUCache<Key: Hashable, Value> {
private final class Node {
let key: Key?
var value: Value?
var next: Node!
weak var prev: Node!
init(_ key: Key?, _ value: Value?) {
self.key = key
self.value = value
}
}
private let capacity: Int
private var nodes: [Key: Node] = [:]
private let sentinel = Node(nil, nil) // next: most recent; prev: least recent
init(capacity: Int) {
precondition(capacity > 0)
self.capacity = capacity
sentinel.next = sentinel
sentinel.prev = sentinel
}
deinit {
sentinel.next = nil
}
func get(_ key: Key) -> Value? {
guard let node = nodes[key] else { return nil }
moveToFront(node)
return node.value
}
func set(_ key: Key, _ value: Value) {
if let node = nodes[key] {
node.value = value
moveToFront(node)
return
}
if nodes.count == capacity {
let oldest = sentinel.prev!
unlink(oldest)
nodes[oldest.key!] = nil
}
let node = Node(key, value)
nodes[key] = node
insertAtFront(node)
}
var keysByRecency: [Key] {
var keys: [Key] = []
var node = sentinel.next!
while node !== sentinel {
keys.append(node.key!)
node = node.next
}
return keys
}
private func unlink(_ node: Node) {
node.prev.next = node.next
node.next.prev = node.prev
}
private func insertAtFront(_ node: Node) {
node.prev = sentinel
node.next = sentinel.next
sentinel.next.prev = node
sentinel.next = node
}
private func moveToFront(_ node: Node) {
unlink(node)
insertAtFront(node)
}
}
let cache = LRUCache<String, Int>(capacity: 2)
cache.set("a", 1)
cache.set("b", 2)
assert(cache.get("a") == 1) // "a" is now the most recent
cache.set("c", 3) // evicts "b", the least recent
assert(cache.get("b") == nil)
assert(cache.keysByRecency == ["c", "a"])
cache.set("a", 10)
assert(cache.get("a") == 10 && cache.keysByRecency == ["a", "c"])The dictionary finds a key’s node in constant time, and the doubly linked list moves that node to the front or removes the oldest in constant time, which a singly linked list could not do without walking to the node before. Real systems, from web browsers to databases, use exactly this pair.
What’s next
Linked lists make get(i) slow. Next lesson: arrays built from scratch,
which make it instant, and the resizing and circular tricks that make
adding to them fast too.