Exercises for Lesson 16

Back to Lesson 16

Exercise 1: Reading recursive functions

Identify the base case, recursive call, and how you know the function works towards the base case for the following recursive functions:

// Computes a*b by adding b to itself a times.
fun mult(a: Int, b: Int): Int {
    if (a == 0) {
        return 0
    }

    return b + mult(a-1, b)
}

// Computes n! = n * (n-1) * (n-2) * ... * 1.
fun fact(n: Int): Int {
    if (n == 1) {
        return 1
    }

    return n * fact(n-1)
}

Back to Lesson 16

Exercise 2: Recursive linked-list traversal

Consider the following function to add up all items in a linked list:

// Node class from LinkedStack implementation.
data class Node<T>(
    var item: T,
    var next: Node<T>?)

// Returns the sum of all items in a linked list (iteratively).
fun sumListIterative(node: Node<Int>?): Int {
    if (node == null) {
        return 0
    }

    var total: Int = 0
    var current: Node<Int>? = node
    while (current != null) {
        total += current.item
        current = current.next
    }

    return total
}

// Returns the sum of all items in a linked list (recursively).
fun sumListRecursive(node: Node<Int>?): Int {
    // TODO: your code here
}

fun main() {
    val node5 = Node<Int>(10, null)
    val node4 = Node<Int>(4, node5)
    val node3 = Node<Int>(2, node4)
    val node2 = Node<Int>(7, node3)
    val node1 = Node<Int>(-5, node2)
    println(sumListIterative(node1))
    // println(sumListRecursive(node1)) // test Part 2a
}

Part 2a: Write some code

Write the recursive function sumListRecursive(node: Node<Int>?): Int.

Afterwards, identify the base case, recursive call, and how you know it works towards the base case.

Part 2b: Next steps

If you finish early, think about: how you would add up all of the even items, or how this changes if the list is circular, like in A4 (Deck of Card Operations).

Back to Lesson 16