IntLists and SLLists
Trace destructive changes to linked lists, build and sum IntLists, feel why the sentinel exists, remove duplicates in place, and an exam-level rearrangement.
- Lessons
- IntLists and SLLists
This discussion goes with Lesson 28. Every solution uses this IntList:
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
}
Q1: What would Swift print?
What would Swift print?
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
}
let list = IntList(1, IntList(2, IntList(3, nil)))
var p: IntList? = list
while let node = p, let next = node.rest {
node.first += next.first
p = next.rest
}
print(list.first, list.rest!.first, list.rest!.rest!.first)Show answer and explanation
Answer3 2 3
The loop adds each node’s successor to it and then jumps two nodes ahead. Node 1 becomes 3; the jump lands on node 3, which has no successor, so the loop ends. Node 2 is never changed.
Q2: Building and summing
Write a static method IntList.of(_:) that builds a list from its arguments,
and sum(), both iteratively and recursively.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
var list: IntList? = nil
for value in values.reversed() {
list = IntList(value, list)
}
return list
}
func sum() -> Int {
var total = 0
var node: IntList? = self
while let current = node {
total += current.first
node = current.rest
}
return total
}
func sumRecursive() -> Int {
first + (rest?.sumRecursive() ?? 0)
}
}
let list = IntList.of(4, 5, 6)!
assert(list.sum() == 15 && list.sumRecursive() == 15)
assert(IntList.of() == nil)Building from the back means each new node goes in front, which is the cheap direction for a singly linked list.
Q3: Why a sentinel?
Write insert(_:at:) for an SLList without a sentinel, where first
is nil for an empty list. Count the special cases, then compare with
Lesson 28’s sentinel version.
Show solution
final class SLList {
private final class Node {
var item: Int
var next: Node?
init(_ item: Int, _ next: Node?) {
self.item = item
self.next = next
}
}
private var first: Node?
private(set) var count = 0
func insert(_ item: Int, at index: Int) {
precondition((0...count).contains(index))
if index == 0 { // special case: no node before
first = Node(item, first)
} else {
var before = first!
for _ in 1..<index {
before = before.next!
}
before.next = Node(item, before.next)
}
count += 1
}
var items: [Int] {
var result: [Int] = []
var node = first
while let current = node {
result.append(current.item)
node = current.next
}
return result
}
}
let list = SLList()
list.insert(2, at: 0)
list.insert(3, at: 1)
list.insert(1, at: 0)
assert(list.items == [1, 2, 3])Inserting at 0 changes first itself, while every other insertion changes some
node’s next, so the two need different code. With a sentinel, “the node
before index 0” is the sentinel, and one loop handles every position.
Q4: Removing duplicates in place
Write removeDuplicates(_:), which destructively removes repeated values
from a sorted IntList, keeping one of each, without creating any nodes.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
var items: [Int] {
var result: [Int] = []
var node: IntList? = self
while let current = node {
result.append(current.first)
node = current.rest
}
return result
}
}
func removeDuplicates(_ list: IntList?) {
var node = list
while let current = node {
while let next = current.rest, next.first == current.first {
current.rest = next.rest
}
node = current.rest
}
}
let list = IntList.of(1, 1, 2, 3, 3, 3, 4)!
removeDuplicates(list)
assert(list.items == [1, 2, 3, 4])
let same = IntList.of(7, 7, 7)!
removeDuplicates(same)
assert(same.items == [7])The inner loop skips over every copy of the current value before the outer loop moves on, so runs of any length collapse to one node. The skipped nodes are freed once nothing points to them.
Q5: Exam-level: evens, then odds
Write evenOdd(_:), which destructively rearranges a list so that the items
at even positions (0, 2, 4, …) come first, in order, followed by the items at
odd positions, in order. [0, 3, 1, 4, 2, 5] becomes [0, 1, 2, 3, 4, 5].
Create no new nodes.
Show solution
final class IntList {
var first: Int
var rest: IntList?
init(_ first: Int, _ rest: IntList?) {
self.first = first
self.rest = rest
}
static func of(_ values: Int...) -> IntList? {
values.reversed().reduce(nil) { IntList($1, $0) }
}
var items: [Int] {
var result: [Int] = []
var node: IntList? = self
while let current = node {
result.append(current.first)
node = current.rest
}
return result
}
}
func evenOdd(_ list: IntList?) {
guard let list, let secondNode = list.rest else { return }
var even = list
var odd = secondNode
while let nextEven = odd.rest {
even.rest = nextEven
even = nextEven
guard let nextOdd = nextEven.rest else {
odd.rest = nil
break
}
odd.rest = nextOdd
odd = nextOdd
}
even.rest = secondNode
if odd.rest === even {
odd.rest = nil
}
}
for (input, expected) in [([0, 3, 1, 4, 2, 5], [0, 1, 2, 3, 4, 5]),
([5, 1, 6], [5, 6, 1]),
([1, 2], [1, 2]),
([8], [8])] {
let list = IntList.of(input[0])!
var tail = list
for value in input.dropFirst() {
tail.rest = IntList(value, nil)
tail = tail.rest!
}
evenOdd(list)
assert(list.items == expected, "\(input)")
}Two pointers walk the list in step: even links each even node to the next
even one, and odd does the same for odd nodes. At the end, the last even
node is linked to the first odd node, which was saved at the start. The
subtle part is the tail: whichever chain finishes last must end with nil,
or the list would loop back on itself, which the tests would catch by never
finishing.