```class Stack<T> { private var first: Node<T>...
# getting-started
m
Copy code
class Stack<T> {
    private var first: Node<T>? = null

    fun push(content: T) {
        if (first == null) {
            first = Node(content)
        } else {
            var node= first
            while (node?.next != null) {
                node = node.next
            }
            node?.content = content
        }
    }}


class Node<T>(var content: T) {
    var next: Node<T>? = null
}
🧵 3
m
@MaximilianH hope this helps ...
class Stack<T> {
private var first: Node<T>? = null
fun push(content: T) {
val newNode = Node(content)
newNode.next = first
first = newNode
}
// Optional: Pop to make it more complete
fun pop(): T? {
val content = first?.content
first = first?.next
return content
}
}
class Node<T>(val content: T) {
var next: Node<T>? = null
}
Key Changes: 1. Push now inserts at the beginning — this is the typical stack behavior. 2. Introduced pop() for completeness (optional). 3. Removed unnecessary traversal of the list (which is inefficient for a stack).
k
@MaximilianH before simplifying, you need to correct the behaviour of your class.
Copy code
class Stack<T> {
    private var first: Node<T>? = null

    fun push(content: T) {
        if (first == null) {
            first = Node(content)
        } else {
            var node= first
            while (node?.next != null) {
                node = node.next
            }
            node?.content = content
At the last line above,
node
points to the last existing node. What this line does is to change the value of the last node to the passed value. You don't want to do that; you want to add a new value to the end. You do that by setting
node?.next
to a new
Node(content)
.