【问题标题】:How to find last node that satisfies where predicate in singly linked list?如何在单链表中找到满足 where 谓词的最后一个节点?
【发布时间】:2021-10-25 21:52:43
【问题描述】:
  1. 编写一个方法“lastWhere”,它接受一个名为“where”的函数,类型为 (T) -> Boolean。该方法返回“where”函数应用到的最后一个类型为 T 的元素。如果没有找到匹配的元素,则返回 null。

  2. 在下面的链表中调用“lastwhere”方法。找出最后一个超过 10 欧元的游戏。

到目前为止,我已经准备好此代码。

我假设我需要编辑的唯一重要代码是任务编号 1) 的“有趣的 lastWhere”

第二个任务要我在 main 函数上实现一种方法来找到最后一个价格低于 10 欧元的游戏。

class LinkedList<T> {
    data class Node<T>(val data: T, var next: Node<T>?)

    private var first: Node<T>? = null

    override fun toString(): String = first?.toString() ?: "-"

    fun isEmpty() = first == null

    fun addLast(data: T) {
        if (first == null) {
            first = Node(data, first)
            return
        }

        var runPointer = first
        while (runPointer?.next != null) {
            runPointer = runPointer.next
        }
        runPointer?.next = Node(data, null)
    }

    fun lastWhere (where: (T) -> Boolean): T? {   // "where" function needs to be implemented
        if (isEmpty()) return null
        else {
            var runPointer = first
            while (runPointer?.next != null ) {
                runPointer = runPointer.next
            }
            return runPointer?.data
        }
    }

}

data class Game(val title: String, val price: Double)

fun main() {
    val list = LinkedList<Game>()
    list.addLast(Game("Minecraft", 9.99))
    list.addLast(Game("Overwatch", 29.99))
    list.addLast(Game("Mario Kart", 59.99))
    list.addLast(Game("World of Warcraft", 19.99))

    var test = list.lastWhere ({it.price >= 10.00})  // This is probably wrong too, since I haven't got task 1) working
    println (test)
}

不胜感激!

【问题讨论】:

  • 我假设这是一些家庭作业 - 你必须运行传递给 lastWhere 的高阶函数,并跟踪传入函数返回的最后一个元素 true(例如.lastValid: T?)。当您用完要评估的元素时,只需返回 lastValid
  • 题外话,但为什么这里 90% 的作业问题都是关于创建自己的 LinkedList 实现的?
  • 好吧,我只能为我说话——LinkedList 现在对我来说是一个新主题,因此是这个问题。我考虑过使用计数器来完成这项任务,但我认为这不是正确的解决方案..
  • @Tenfour04 猜测他们仍然教授基本的数据结构,并让你自己动手演示这个概念,而不是“只使用语言方便地为你提供的任何东西”。可能与每个人都对ArrayLists 如此狂热的原因相同!也许一些大型在线课程现在正在涵盖它

标签: kotlin linked-list higher-order-functions


【解决方案1】:

由于您只存储对第一个节点的引用,因此您别无选择,只能首先开始并迭代。您还必须保留对满足 where 谓词的最后一项的引用,并在每次迭代时不断更新此引用。

fun lastWhere (where: (T) -> Boolean): T? { 
    var runPointer = first
    var item: T? = null    // init item to null, if nothing is found we return null
    while (runPointer != null ) {
        // For every node, execute the where function and if it returns true
        // then update the return value 
        if(where(runPointer.data)) { item = runPointer.data }
        runPointer = runPointer.next
    }
    return item
}

【讨论】:

    猜你喜欢
    • 2018-09-29
    • 2017-12-07
    • 2011-11-04
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多