我正在尝试在 Kotlin 中从头开始创建 LinkedList 数据结构。在构建 Node 对象时,它不允许我将 head 分配给下一个参数并给出以下错误:
Error:Error:line (21)Kotlin: Type inference failed: Cannot infer type parameter T in constructor Node(value: T#1 (type parameter of Node), next: Node? = ...) None of the following substitutions (T#2 (type parameter of LinkedList),Node?) (Int,Node?) can be applied to (Int,Node?)
Node.kt
data class Node<T>(var value: T, var next: Node<T>? = null) {
override fun toString(): String {
return if (next != null) {
"$value -> ${next.toString()}"
} else {
"$value"
}
}
}
LinkedList.kt
class LinkedList<T> {
private var head: Node<T>? = null
private var tail: Node<T>? = null
private var size = 0
fun isEmpty(): Boolean {
return size == 0
}
override fun toString(): String {
if (isEmpty()) {
return "Empty List"
} else {
return head.toString()
}
}
fun push(value: T) {
head = Node(value = 5, next = head)
if (tail == null) {
tail = head
}
size++
}
}
谁能解释一下我做错了什么?
最佳答案
在您的 LinkedList::push(value: T)
方法中,您可以:
head = Node(value = 5, next = head)
我不确定 value = 5
来自哪里(也许你在调试),但它应该是:
head = Node(value = value, next = head)
关于android - 在 Kotlin 中构建 LinkedList 时出现类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114402/