MaximilianH
05/25/2025, 6:41 AM?.
. Is there a better way to do this?Martin Benda
05/25/2025, 7:51 AMnode?.next = Node(content)
instead of node?.content = content
. As for the smart-cast to Node<T>
, the compiler probably does not do it because of the node = node?.next
assignment in the loop. You could use the !!
operator instead of ?.
, but I'm not sure if there is a better way.Martin Benda
05/25/2025, 7:52 AMfun push(content: T) {
if (first == null) {
first = Node(content)
} else {
var node = first!!
while (node.next != null) {
node = node.next!!
}
node.next = Node(content)
}
}}
Edwar D Day
05/25/2025, 8:12 AMnext
, but don't know, if a different Thread
or whatever changes the field again between check an assignment. You might solve this by introducing an intermediate local variable to hold the value, you check against.
class Stack<T> {
private var first: Node<T>? = null
fun push(content: T) {
var h = first
if (h == null) {
first = Node(content)
} else {
var node = h
h = h.next
while (h != null) {
node = h
}
node.content = content
}
}
}
class Node<T>(var content: T) {
var next: Node<T>? = null
}