Part 17 / Topic 8 of 12
Build your own linked list
A linked list is a chain of Nodes, each holding a value and a reference to the next node — no contiguous block of memory the way an array needs. Kotlin's standard library has no built-in linked-list type at all (the ArrayDeque from section 4 is array-backed, despite the name "deque" suggesting otherwise), so writing a singly linked list by hand once is what makes "insert at the head is O(1)" and "delete needs the previous node, which a singly linked list can't look up backward" stop being trivia you memorized and start being something you've actually hit mid-method.
Think of a treasure hunt where each clue only tells you where the next clue is: finding clue #1 is instant, but to remove clue #5 you need to already be holding clue #4 — there's no way to jump back to it from #5 itself.
class Node<T>(val value: T) {
var next: Node<T>? = null
}
fun addFirst(value: T) { // O(1): no shifting, unlike an array's insert-at-0
val node = Node(value)
node.next = head
head = node
if (tail == null) tail = node
size++
}
$ kotlinc LinkedListDemo.kt -include-runtime -d ll.jar
$ java -jar ll.jar
bus stops after addLast x3: [Pune Station -> Swargate -> Hadapsar] (size 3)
after addFirst("Depot"): [Depot -> Pune Station -> Swargate -> Hadapsar]
remove("Swargate") -> true: [Depot -> Pune Station -> Hadapsar]
removeFirst() -> "Depot": [Pune Station -> Hadapsar]
after reverse(): [Hadapsar -> Pune Station]
-- cycle detection (Floyd's slow/fast pointers) --
no-cycle list has a cycle: false
hand-built cyclic list has a cycle: true
reverse() relinks every next pointer in a single O(n) pass with no extra list — three pointers (previous, current, the saved next) marching together. Cycle detection (Floyd's algorithm, also called the tortoise and hare) uses a slow pointer moving one step and a fast pointer moving two: on a list with a genuine loop, the fast pointer eventually laps the slow one and they land on the same node (checked with ===, Kotlin's referential-equality operator, not ==, which would call equals() on the values instead of comparing node identity); on a list with no loop, the fast pointer simply reaches the end first.
Full program: examples/linked-lists/LinkedListDemo.kt.
Done here? The practice set for Part 17 — including the solutions — is on the part page.