【发布时间】:2020-08-20 04:46:36
【问题描述】:
我正在尝试编写一个函数,该函数确定给定的链表是否已排序(降序)。
给定列表 1:8 -> 5 -> 3 -> null (true)
给定 list2:8 -> 6 -> 10 -> 3 -> null (false)
给定 list3:8 -> 8 -> 3 -> null (true)
这是我目前的做法:
class Linkedlist {
var head: Node? = null
data class Node(val value: Int, var next: Node?)
// Current approach
fun isListSorted(): Boolean {
// If list is empty
if (head == null) return true
var curr = head
while(curr != null) {
curr = curr.next
if (curr?.value!! <= curr?.next?.value!!) return false else return true
}
return true
}
}
这里是我的主要内容:
fun main() {
val list1 = Linkedlist()
list1.append(8)
list1.append(5)
list1.append(3)
val list2 = Linkedlist()
list2.append(8)
list2.append(6)
list2.append(10)
list2.append(3)
val list3 = Linkedlist()
list3.append(8)
list3.append(8)
list3.append(3)
}
我得到一个 NullPointerException。我究竟做错了什么?我感谢每一个帮助!
【问题讨论】:
标签: sorting kotlin linked-list